1. 程式人生 > 其它 >不穩定排序,選擇排序,快速排序,快速排序優化, 內部排序

不穩定排序,選擇排序,快速排序,快速排序優化, 內部排序

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

#define swape(a, b) ({\
        __typeof (a) temp;\
        temp = a;\
        a = b;\
        b = temp;\
})
#define TES(arr, max, func, args...) {\
        int *num = (int *)malloc(sizeof(int) * max);\
        memcpy(num, arr, sizeof(int) * max);\
        func(args);\
        printf(#func" ");\
        output(num, max);\
        printf("\n");\
        free(num);\
}

void select_sort(int *num, int m) {
        for (int i = 0, ind, j; i < m - 1; i++) {
                ind = i;
                for (j = i + 1; j < m; j++) num[ind] > num[j] && (ind = j);
                swape(num[ind], num[i]);
        }
        return ;
}

/*
 * 普通快速排序
void quick_sort(int *num, int ml, int m) {
        int l = ml, r = m, sk = num[l];
        while(l < r) {
                while(num[r] >= sk) r--;
                l <= r && (num[l++] = num[r]);
                while(l < r && num[l] < sk) l++;
                l <= r && (num[r--] = num[l]);
        }
        num[l] = sk;
        l > ml && (quick_sort(num, ml, l - 1), 1);
        l < m && (quick_sort(num, l + 1, m), 1);
        return ;
}
*/

/*
 * 優化後的快速排序
 * 單邊遞迴
 * 基準值優化
 * 取消監督
*/  
void quick_sort(int *num, int ml, int m) {
        while (ml < m) {
                int l = ml, r = m, sk = num[(l + r) >> 1];
                do {
                        while (num[l] < sk) l++;
                        while (num[r] > sk) r--;
                        if (l <= r) {swape(num[l], num[r]); l++, r--;}
                } while (l <= r);
                quick_sort(num, ml, r);
                ml = l;
        }
        return ;
}

void output(int *num, int m) {
        for (int i = 0; i < m; i++, m - i && printf(" ")) printf("%d", num[i]);
        printf("\n");
        return ;
}

void input(int *num, int m) {
        for (int i = 0; i < m; i++) num[i] = rand() % 100;
        return ;
}

int main() {
        srand(time(0));
#define MAX 10
        int arr[MAX], op = rand() % 2;
        input(arr, MAX), output(arr, MAX);
        for (int i = 0; i < MAX; i++, op = rand() % 2)
        switch(op) {
                case 0: TES(arr, MAX, select_sort, num, MAX);
                        break;
                case 1: TES(arr, MAX, quick_sort, num, 0, MAX - 1);
                        break;
        }
#undef MAX
        return 0;
}