排序算法 之 (快速排序)

10.3、快速排序

算法思想

在待排序表[1...n]中任取一个元素pivot作为枢轴(基准,通常去首元素),通过一趟排序将待排序表划分为独立的两部分L[1...k-1]和L[k+1...n],使得L[1...k-1]中所有元素小于pivot,L[k+1...n]中所有元素都大于等于pivot,则pivot放在最终位置L(k)上,这个过程称为一次划分。然后分别递归地对两个子表重复上述过程,直到每部分内只有一个元素或者空为止,即所有元素放到其最终位置上。

注意:快排是不稳定

算法思想图解

快速排序代码实现

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

#define boolean int
#define false 0;
#define true 1;

//快速排序:nums:待排序数组;low:表示低指针;high:表高指针;返回排序后的枢轴位置
int partition(int nums[],int low,int high){
    int privot = nums[low];//第一个元素为枢轴
    while(low < high){
        while(low < high && nums[high] >= privot) high--;
        nums[low] = nums[high];//比枢轴小的元素移动到左端
        while(low < high && nums[low] <= privot) low++;
        nums[high] = nums[low];//比枢轴大的元素移动到右端
    }
    nums[low] = privot;//把枢轴方法最终的位置
    return low;//返回枢轴位置
}
void QuickSort(int nums[],int low,int high){
    if(low < high){
        int pivotpos = partition(nums,low,high);
        QuickSort(nums,low,pivotpos-1);
        QuickSort(nums,pivotpos+1,high);
    }
}

int main(){
    int nums[] = {49,38,65,97,76,13,27,49};
    int length = 8;
    printf("快速排序前:");
    for(int i = 0; i < length ;i++){
        printf("%d ",nums[i]);
    }
    QuickSort(nums,0,length-1);
    printf("\n");
    printf("快速排序后:");
    for(int i = 0; i < length ;i++){
        printf("%d ",nums[i]);
    }

    return 0;
}
//结果:
快速排序前:49 38 65 97 76 13 27 49 
快速排序后:13 27 38 49 49 65 76 97 
posted @ 2023-03-15 18:12  水三丫  阅读(25)  评论(0编辑  收藏  举报