[C Language] sorts the names of five countries in detail.
Note: code is compiled through TDM-GCC4.9.2
Original question: there are five country names: "China", "America", "Australia", "France", and "Germany. Design a program to sort it in alphabetical order and output the results.
Idea: using traditional sorting methods to store strings in character Arrays for exchange will make the program complicated and difficult to compile and check. It can be saved in the string pointer array. When sorting, you only need to apply the sorting method of the original one-dimensional array to swap the order of the two string pointers in the pointer array, and the program becomes very simple.
DESIGN: write two custom functions: void sort (char * name []) for sorting, void prins (char * put []) for output. Assign values to strings in the main () function, and call two custom functions in sequence to complete the design.
Code:
1 # include <stdio. h> 2 # include <stdlib. h> 3 4 # define N 5 5 6 void sort (char * name []) // sort 7 {8 int I, j; 9 char * sp; // for temporary exchange 10 for (I = 0; I <N-1; I ++) // sort 11 {12 for (j = I + 1; j <N; j ++) 13 {14 if (strcmp (name [I], name [j])> 0) 15 {// when name [I]> name [j], exchange to sort ① 16 sp = name [I]; 17 name [I] = name [I + 1]; 18 name [I + 1] = sp; 19} 20} 21} 22} 23 24 void prins (char * put []) // output 25 {26 int I; 27 for (I = 0; I <N; I ++) 28 printf ("% s", put [I]); // cannot write * put [I] ② 29} 30 31 int main () {32 char * spa [] = {"China", "America", "Australia", "France", "Germany"}; 33 sort (spa ); 34 prins (spa); 35 getch (); 36 return 0; 37}
Running result: America Australia China France Germany
Explanation: ① In strcmp (str1, str2,
When str1> str2, the function value is greater than 0;
When str1 = str2, the function value is 0;
When str1 <str2, the function value is <0;
② Because put [I] is a string pointer, the string Pointer Points to the address of a character constant. According to the printf () function prototype, * put [I] cannot be used here. otherwise, an error occurs.
Conclusion: To clarify the principles of string pointers, build a pointer array for Direct Sequence swaps of string pointers, and apply the one-dimensional array sorting method to sort string pointers.