排序

#include <cstdio>
#include <cstdlib>
const int MAXN = 600;
int n, num[MAXN];
void ShellInsert(int *num, int dk){
    int i, j;
    for(i = dk + 1; i <= n; i++)
        if(num[i] < num[i-dk]){
            num[0] = num[i];
            for(j = i - dk; j>0 && num[0] < num[j]; j -= dk)
                num[j+dk] = num[j];
            num[j+dk] = num[0];
        }    
}

void ShellSort(int *num, int k){
    for(int i = 0; i <= k; i++)
        ShellInsert(num, i); 
}

void HeapAdjust(int s, int m){
    num[0] = num[s];
    for(int j = 2*s; j <= m; j *= 2){
        if(j < m && num[j] < num[j+1])
            ++j;
        if(num[0] >= num[j])
            break;
        num[s] = num[j]; 
        s = j;
    }    
    num[s] = num[0];
}

void CreatHeap(){
    for(int i = n/2; i > 0; i--)
        HeapAdjust(i, n);
}

void HeapSort(){
    CreatHeap();
    for(int i = n; i > 1; i--){
        int x = num[1];
        num[1] = num[i];
        num[i] = x;
        HeapAdjust(1, i - 1); 
    }
}

int Partition(int low, int high){
    num[0] = num[low];
    while(low < high){
        while(low < high && num[high] >= num[0])
            high--;
        num[low] = num[high];
        while(low < high && num[low] <= num[0])
            low++;
        num[high] = num[low];
    }
    num[low] = num[0];
    return low;
}

void Qsort(int low, int high){
    //int low = 1, high = n;
    if(low < high){
        int pivotloc = Partition(low, high);
        Qsort(low, pivotloc-1);
        Qsort(pivotloc+1, high);
    }    
}

void QuickSort(){
    Qsort(1, n);    
} 

void Printfnum(){
    for(int i = 1; i <= n; i++)
        printf(i==n?"%d
":"%d ", num[i]);
}

void creatnum(){
    num[0] = 0;
    printf("输入待排序序列个数
");
    scanf("%d", &n);
    printf("输入待排序序列
"); 
    for(int i = 1; i <= n; i++)
        scanf("%d", &num[i]);
}
void operation(){
    printf("1.输入待排序序列
2.快排
3.Shell排序
4.堆排序
");
    int M;
    scanf("%d", &M);
    system("cls");
    switch(M){
        case 1:
            creatnum();
            system("cls");
            break;
        case 2: 
            printf("快排所得结果为
");
            QuickSort();
            Printfnum();
            system("pause");
            system("cls");
            break;
        case 3:
            Printfnum();
            printf("堆排序所得结果为
");
            HeapSort();
            Printfnum();
            system("pause");
            system("cls");
            break;
        case 4:
            int Q;
            printf("输入shell排序所需初始增量
");
            scanf("%d", &Q);
            printf("shell排序所得结果为
");
            ShellSort(num, Q);
            Printfnum();
            system("pause");
            system("cls");
            break;
    }
    operation();
}

int main(){
    operation();
}
原文地址:https://www.cnblogs.com/soTired/p/5057090.html