交换排序

2019-01-19  本文已影响0人  Pwnmelife
#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;
}
上一篇 下一篇

猜你喜欢

热点阅读