C 语言快速排序算法

全栈 shanhuhai 1739℃

快速排序法的c语言实现,下面的代码包含了正序与逆序的实现,
代码如下:

#include <stdio.h>
int print_array(int array[]){
    int i;    
    for(i = 0; i < 10; i++){
        printf("%4d", array[i]);
    }
    return 0;
}

int quick_sort(int s[], int left, int right){
    if(left < right) {
        int i = left;
        int j = right;
        int x = s[left];
        
        while(i < j) {
            while(i < j && s[j] >= x) 
                j--;
            if(i < j) {
                s[i] = s[j];
                i++;
            }
            while(i < j && s[i] < x) 
                i++;
            if(i < j) {
                s[j] = s[i];
                j--;
            }
        }
        s[i] = x;
        quick_sort(s, left, i - 1);
        quick_sort(s, i + 1, right);
    }
    return 0;
}

int quick_sort_reverse(int s[], int left, int right){
    if(left < right) {
        int i = left;
        int j = right;
        int x = s[left];
        
        while(i < j) {
            while(i < j && s[j] <= x) 
                j--;
            if(i < j) {
                s[i] = s[j];
                i++;
            }
            while(i < j && s[i] > x) 
                i++;
            if(i < j) {
                s[j] = s[i];
                j--;
            }
        }
        s[i] = x;
        quick_sort_reverse(s, left, i - 1);
        quick_sort_reverse(s, i + 1, right);
    }
    return 0;
}


int main() {
    int array[10] = {49, 38, 65, 97, 48, 13, 27, 11, 56, 45};
    int maxlen = sizeof(array)/sizeof(int);

    print_array(array);
    printf("\n");
    quick_sort(array, 0, maxlen - 1);
    print_array(array);
    printf("\n");
    quick_sort_reverse(array, 0, maxlen - 1);
    print_array(array);
    return 0;
}

转载请注明:大后端 » C 语言快速排序算法

喜欢 (1)or分享 (0)