【排序】快速排序

来源:互联网 发布:小白素材vip源码 编辑:程序博客网 时间:2024/04/30 11:37
#include<iostream>using namespace std;int pnumsrtition(int nums[], int low, int high){    int pivot_key = nums[low];//用区间的第1个记录作为基准    while (low < high){//从区间两端交替向中间扫描,直到low=high为止        while (low < high&&nums[high] >= pivot_key)            high--;//从右向左扫描,查到第1个关键字小于pivot_key的记录nums[hgih]        if (low < high)            nums[low++] = nums[high];//相当于交换nums[low]和nums[high]        while (low < high&&nums[low] <= pivot_key)            low++;        if (low < high)            nums[high--] = nums[low];    }    nums[low] = pivot_key;//基准记录已被最后定位    return low;}void quick_sort(int nums[], int low, int high){    int pivot; //划分后的基准记录的位置    if (low < high){        pivot = pnumsrtition(nums, low, high);//做划分        quick_sort(nums, low, pivot - 1);        quick_sort(nums, pivot + 1, high);    }}void print_numsrrnumsy(int nums[], int len){    for (int i = 0; i < len; i++)        cout << nums[i] << ' ';    cout << endl;}int main(){    int nums[] = { 9, 1, 5, 8, 3, 7, 4, 6, 2 };    int len = sizeof(nums) / sizeof(int);    quick_sort(nums, 0, len - 1);    print_numsrrnumsy(nums, len);    return 0;}

0 0
原创粉丝点击