美文网首页
交换排序

交换排序

作者: Pwnmelife | 来源:发表于2019-01-19 20:46 被阅读0次
    #include <stdio.h>
    #include <stdlib.h>
    
    void Bubble_Sort_1(int k[], int n);
    void Bubble_Sort_2(int k[], int n);
    void Bubble_Sort_3(int k[], int n);
    void QuickSort(int k[], int low, int high);
    int Partition(int k[], int low, int high);
    
    int main()
    {
        int k[] = { 50,26,38,80,70,90,8,30,40,20 };
        Bubble_Sort_3(k, 10);
        printf("The sorted result: \n");
        for (int i = 0; i < 10; i++) {
            printf("%d ", k[i]);
        }
        printf("\n\n");
    }
    
    void Bubble_Sort_1(int k[], int n) {
        int temp;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (k[i] > k[j]) {
                    temp = k[i];
                    k[i] = k[j];
                    k[j] = temp;
                }
            }
        }
    }
    void Bubble_Sort_2(int k[], int n) {
        int temp;
        for (int i = 0; i < n; i++) {
            for (int j = n-1; j>i; j--) {
                if (k[j] < k[j-1]) {
                    temp = k[j-1];
                    k[j-1] = k[j];
                    k[j] = temp;
                }
            }
        }
    }
    void Bubble_Sort_3(int k[], int n) {
        int temp;
        bool flag = true;
        for (int i = 0; i < n && flag; i++) {
            for (int j = n - 1; j > i; j--) {
                flag = 0;
                if (k[j] < k[j - 1]) {
                    flag = 1;
                    temp = k[j - 1];
                    k[j - 1] = k[j];
                    k[j] = temp;
                }
            }
        }
    }
    void QuickSort(int k[], int low, int high) {
        if (low < high) {
            int pivotpos = Partition(k, low, high);
            QuickSort(k, low, pivotpos - 1);
            QuickSort(k, pivotpos + 1, high);
        }
    }
    int Partition(int k[], int low, int high) {
        int pivot = k[low];
        while (low < high) {
            while (low < high && k[high] >= pivot) --high;
            k[low] = k[high];
            while (low < high && k[low] <= pivot) ++low;
            k[high] = k[low];
        }
        k[low] = pivot;
        return low;
    }
    

    相关文章

      网友评论

          本文标题:交换排序

          本文链接:https://www.haomeiwen.com/subject/feazdqtx.html