- 论坛徽章:
- 0
|
5可用积分
各位好,我这里有个字符串选择排序的问题向各位请教。问题是,按字符在英文字母表中的顺序排序出错。代码如下:
/* Test with sorting arrays in a array*/
#include <stdio.h>
#define N 10
#define M 81
void shwstr(char * str[], int n);
char ** selectsort(char * str[],int n);
int main(void){
char arr[N][M];
char *arp[M], ** app;
int cnt = 0;
printf("\nEnter a maximum of %d lines.\nPress Enter at the biginning of a "
"line to quit.\n");
while(cnt < N && gets(arr[cnt]) != NULL && arr[cnt][0] != '\0'){
arp[cnt] = arr[cnt];
cnt++;
}
printf("\nBefore sorting, the lines entered are:\n");
shwstr(arp,cnt);
app = selectsort(arp,cnt);
printf("\nAfter sorting, the lines entered are:\n");
shwstr(app,cnt);
puts("\nDone!");
getch();
return 0;
}
char ** selectsort(char * str[], int n){
int k,j,max;
char * temp;
for(k = 0; k < n - 1; k++){
max = k;
for(j = k+1; j < n; j++)
if(strcmp(str[k],str[j]) > 0)
max = j;
temp = str[k];
str[k] = str[max];
str[max] = temp;}
return str;
}
void shwstr(char * str[],int n){
int k;
for(i = 0; i < n; i++)
puts(str[k]);
}
运行程序情况:
Enter a maximum of 10 lines.
Press Enter at the biginning of a line to quit.
A man was sitting in the chair.
He was smoking a camel cigarette.
A woman came into the scene.
She was wearing a red blouse.
A child was standing at the center of the room.
He was playing his toys.
Before sorting, the lines entered are:
A man was sitting in the chair.
He was smoking a camel cigarette.
A woman came into the scene.
She was wearing a red blouse.
A child was standing at the center of the room.
He was playing his toys.
After sorting, the lines entered are:
A child was standing at the center of the room.
He was playing his toys.
A man was sitting in the chair.
He was smoking a camel cigarette.
A woman came into the scene.
She was wearing a red blouse.
Done!
[ 本帖最后由 mcmay 于 2008-3-29 21:10 编辑 ] |
|