C-插入排序、归并排序、快速排序(代码记录)

目的:备忘
以下直接贴代码:

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

void myswap(int * a, int * b) {
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

void insertion_sort(int * Ar, const int low, const int high) {
    int tmp, i, j;
    for(i = low + 1; i <= high; i++) {
        tmp = Ar[i];
        for(j = i; j > 0 && Ar[j - 1] > tmp; j--)
            Ar[j] = Ar[j - 1];
        Ar[j] = tmp;
    }
}

void median3(int * Ar, const int low, const int high) {
    int mid = (low + high) / 2;
    if(Ar[low] > Ar[mid])
        myswap(&Ar[low], &Ar[mid]);
    if(Ar[low] > Ar[high])
        myswap(&Ar[low], &Ar[high]);
    if(Ar[mid] > Ar[high])
        myswap(&Ar[mid], &Ar[high]);
    myswap(&Ar[mid], &Ar[high - 1]);
}

void quick_sort(int * Ar, const int low, const int high) {
    int cutoff = 3, i, j;
    if(low + cutoff < high) {
        median3(Ar, low, high);
        i = low; j = high - 1;
        while(1) {
            while(Ar[++i] < Ar[high - 1]) {}
            while(Ar[--j] > Ar[high - 1]) {}
            if(i < j)
                myswap(&Ar[i], &Ar[j]);
            else
                break;
        }
        myswap(&Ar[i], &Ar[high - 1]); // 这一步,交换枢纽元与i或j上的元素,如果枢纽元在后,则交换i的,如果枢纽元在前,则交换j的
                                       // 否则就会把大的元素交换到比枢纽元小的部分中,或者就会把小的元素交换到比枢纽元大的部分中
        quick_sort(Ar, low, i - 1);
        quick_sort(Ar, i + 1, high);
    }
    else
        insertion_sort(Ar, low, high);
}

void Merge(int * Ar, int * tmpA, const int low, const int mid, const int high) {
    int i, j, k;
    k = low; i = low; j = mid + 1;
    while(i <= mid && j <= high) {
        if(Ar[i] < Ar[j])
            tmpA[k++] = Ar[i++];
        else
            tmpA[k++] = Ar[j++];
    }
    while(i <= mid)
        tmpA[k++] = Ar[i++];
    while(j <= high)
        tmpA[k++] = Ar[j++];
    for(i = low; i <= high; i++)
        Ar[i] = tmpA[i];
}

void Msort(int * Ar, int * tmpA, const int low, const int high) {
    int mid = (low + high) / 2;
    if(low < high) {
        Msort(Ar, tmpA, low, mid);
        Msort(Ar, tmpA, mid + 1, high);
        Merge(Ar, tmpA, low, mid, high);
    }
}

void merge_sort(int * Ar, const int low, const int high) {
    int * tmpA = (int *)malloc((high - low + 1) * sizeof(int));
    if(tmpA != NULL) {
        Msort(Ar, tmpA, low, high);
        free(tmpA);
    }
    else
        printf("Space not enough!\n");
}


int main() {
    int i, N;
    scanf("%d", &N);
    int A[N];
    for(i = 0; i < N; i++)
        scanf("%d", &A[i]);
    quick_sort(A, 0, N - 1);
    //merge_sort(A, 0, N - 1);
    for(i = 0; i < N; i++)
        printf("%d\n", A[i]);
    return 0;
}
点赞