#include <stdio.h> #include <string.h>
// 调试输出宏定义 #ifdef DEBUG #define debug(...) \ do { \ printf(__VA_ARGS__); \ } while (0) #else #define debug(...) #endif
// 双向冒泡排序 void bubble_sort(unsigned int a[], unsigned int n) { unsigned int top = 0; unsigned int bottom = n - 1; unsigned int mark = top; unsigned int tmp; unsigned int i;
do {
// 下沉 for (i = top; i < bottom; i++) { if (a[i] > a[i+1]) { tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; mark = i; debug("v%d\n", mark); } } bottom = mark;
// 上浮 debug("%2d -- %2d\n", top, bottom); for (i = bottom; i > top; i--) { if (a[i-1] > a[i]) { tmp = a[i]; a[i] = a[i-1]; a[i-1] = tmp; mark = i; debug("^%d\n", mark); } } top = mark; debug("%2d -- %2d\n", top, bottom); } while (top < bottom); }
// 直接插入排序 void insert_sort(unsigned int a[], unsigned int n) { unsigned int i, j; unsigned int tmp;
for (i = 1; i < n; i++) { tmp = a[i]; j = i; while (j > 0 && a[j-1] > tmp) { a[j] = a[j-1]; j--; } a[j] = tmp; } }
|