通用的排序算法
- /* The Shaker Sort. */
- void shaker(char *items, int count)
- {
- register int a;
- int exchange;
- char t;
- do {
- exchange = 0;
- for(a=count-1; a > 0; --a) {
- if(items[a-1] > items[a]) {
- t = items[a-1];
- items[a-1] = items[a];
- items[a] = t;
- exchange = 1;
- }
- }
- for(a=1; a < count; ++a) {
- if(items[a-l] > items[a]) {
- t = items[a-l];
- items[a-1] = items[a];
- items[a] = t;
- exchange = 1;
- }
- }
- } while(exchange); /* sort until no exchanges take place */
- }
- /* The Selection Sort. */
- void select(char *items, int count)
- {
- register int a, b, c;
- int exchange;
- char t;
- for(a=0; a < count-1; ++a) {
- exchange = 0;
- c = a;
- t = items[a];
- for(b=a+1; b < count; ++b) {
- if(items[b] < t) {
- c = b;
- t = items[b];
- exchange = 1;
- }
- }
- if(exchange) {
- items[c] = items[a];
- items[a] = t;
- }
- }
- }
- /* The Insertion Sort. */
- void insert (char *items, int count)
- {
- register int a, b;
- char t;
- for(a=1; a < count; ++a) {
- t = items[a];
- for(b=a-1; (b >= 0) && (t < items[b]); b--)
- items[b+1] = items[b];
- items[b+1] = t;
- }
- }
- /* The Shell Sort. */
- void shell(char *items, int count)
- {
- register int i, j, gap, k;
- char x, a[5];
- a[0]=9; a[1]=5; a[2]=3; a[3]=2; a[4]=1;
- for(k=0; k < 5; k++) {
- gap = a[k];
- for(i=gap; i < count; ++i) {
- x = items[i];
- for(j=i-gap; (x < items[j]) && (j >= 0); j=j-gap)
- items[j+gap] = items[j];
- items[j+gap] = x;
- }
- }
- }
- /* Quicksort setup function. */
- void quick(char *items, int count)
- {
- qs(items, 0, count-1);
- }
- /* The Quicksort. */
- void qs(char *items, int left, int right)
- {
- register int i, j;
- char x, y;
- i = left; j = right;
- x = items[(left+right)/2];
- do {
- while((items[i] < x) && (i < right)) i++;
- while((x < items[j]) && (j > left)) j--;
- if(i <= j) {
- y = items[i];
- items[i] = items[j];
- items[j] = y;
- i++; j--;
- }
- } while(i <= j);
- if(left < j) qs(items, left, j);
- if(i < right) qs(items, i, right);
- }
复制代码 |