First, quick sort
( 1) Arrange integers:
#include <stdio.h> #include <stdlib.h> #include <string.h> int com_int (const void *ELEM1, const void * ELEM2) {return * (int *) ELEM1-* (int *) elem2;} int main () {int arr[] = {1, 3, 5, 7, 2, 4, 6, 8};int i = 0;qsort (arr,sizeof (arr)/sizeof (arr[0]), sizeof (Arr[0]), Com_int ); for (i = 0; i < sizeof (arr)/sizeof (arr[0]); i++) {printf ("%d", Arr[i]);} printf ("\ n"); system ("pause"); return 0;}
Operation Result:
1 2 3 4 5 6 7 8
( 2) To arrange multiple strings:
#include <stdio.h> #include <stdlib.h> #include <string.h>int com_str (const void *ELEM1, const void * ELEM2) {return strcmp ((char *) * (int *) ELEM1, (char *) * (int *) ELEM2); int main () {char *arr[] = {"BBBB", "AAAA", "dddd", "CCCC"};int i = 0;qsort (arr,sizeof (arr)/sizeof (arr[0]), sizeof (Arr[0]), COM_STR); for (i = 0; i < sizeof (arr)/sizeof (arr[0]); i++) {printf ("%s", Arr[i]);} printf ("\ n"); system ("pause"); return 0;}
Run Results :
AAAA bbbb CCCC dddd
Second, Bubble Row String
#include <stdio.h> #include <stdlib.h> #include <string.h> Void bubble_sort (Char*str[], int sz) {int i = 0;int j = 0;for (i = 0; i < sz - 1; i++) {for (j = 0; j < sz - 1 - i; j++) {if (strcmp (str[j], str[j + 1]) >0) {char*tmp = null;tmp = str[j];str[j] = str[j + 1];str[j + 1] = tmp;}}}} Int main () {char*str[] = { "Hello", "World", "to", "bit", "welcome" };//pointer Array int i = 0;bubble_sort (str, sizeof (str) / sizeof (str[0]));for (I = 0; i < sizeof (str) / sizeof (str[0]); i++) {printf ("%s ", str[i]);} printf ("\ n"); system ("pause"); return 0;}
Results:
bit hello to welcome world
Optimized bubbling (high quality):
#include <stdio.h> #include <stdlib.h> #include <string.h>int com_str ( CONST&NBSP;VOID&NBSP;*ELEM1,&NBSP;CONST&NBSP;VOID&NBSP;*ELEM2) {return strcmp ((char *) * (int *) elem1, (char *) * (int *) elem2);} void swap (Char *p1, char *p2, size_t sz) {size_t i = 0;for (i = 0; i<sz; i++) {char tmp = * (p1+i); * (P1+i) = * (p2+i); * (P2+i) = tmp;}} void bubble_sort (void *base, size_t num, size_t width,int (*CMP) ( CONST&NBSP;VOID&NBSP;*ELEM1,&NBSP;CONST&NBSP;VOID&NBSP;*ELEM2)) {size_t i = 0;size_t j = 0;for (i = 0; i < num-1; i++) {for (j = 0; j < num-1-i; j++) {if (CMP (char *) base+ width*j, (char *) base+width* (j+1)) > 0) {Swap ((char *) base+ width*j, (char *) base+width* (j+1), width);}}} int main () {char *arr[] = {"bbbb", "AAAA", "dddd", "CCCC"};int i = 0; Bubble_sort (arr,sizeof (arr)/sizeof (arr[0]), sizeof (Arr[0]), com_str);for (i = 0; i < sizeof (arr) / sizeof (arr[0]), i++) {printf ("%s ", arr[i]);} printf ("\ n"); system ("pause"); return 0;}
Quick-row and bubbling high-quality sorting