Write a bubbling sort that can either write a string or write a number.
1). A function pointer needs to be implemented to pass in the entry address of the function at the time of sorting.
void sort (Void *base, int len, int width, int (*CMP) (const void*, const void*)) { assert (Base); int i = 0; int j = 0; for (i = 0; i < len; i++) { for (j = 0; j < len - 1 - j; j++) { if (CMP ( (char *) base + width*j, (char *) base + width* (j + 1)) >0) { swap ((char *) base + width*j, (char *) base + width* (j + 1), width); } } } }
implementing the main logic of the Code
1). parameter settings, one can receive any type of pointer, data size, type size, function declaration.
2). You need to implement a comparison string function, an integer comparison function, and a swap function.
Compare String Functions
int str_cmp (const void *P1, const void *P2) {assert (P1); ASSERT (P2); Return strcmp ((char *) (* (int *) p1), (char *) (* (int *) p2)); }
functions for comparing integral types
int int_cmp (const void *P1, const void *P2) {assert (P1); ASSERT (P2); if (* (int *) p1 > * (int *) p2) {return 1; } else if (* (int *) P1 = = * (int *) p2) {return 0; } else {return-1; } }
the implementation of Exchange function
void swap (void *p1, void *p2, int size) {assert (P1); ASSERT (P2); int i = 0; for (i = 0; i < size; i++) {Char tmp = * (char *) p1 + i); * ((char *) p1 + i) = * ((char *) P2 + i); * ((char *) P2 + i) = tmp; } }
When you need to compare strings, you need to pass str_cmp in when you pass the arguments. In the same vein, you need to compare integer numbers, and you need to pass int_cmp in, notice the function arguments.
above is that I am in the process of learning some experience summary. Of course, my ability is limited, there will inevitably be flaws, I hope you can correct me.
This article is from the "make a small driver" blog, please be sure to keep this source http://10799170.blog.51cto.com/10789170/1718853
Bubble sort can either arrange strings or arrange strings