c++ 快速排序 数据结构与算法

原理(升序):

1.第一趟排序先将数组第一个数用pivot作为基准保存

2.先从最右侧开始,若遇到的元素比pivot小,则将此元素赋值给当前i代表的元素(这里的赋值就是交换,下同)

3.再从左侧开始,若遇到的元素比pivot大,则将此元素赋值给当前j代表的元素

4处理左边子序列

5.处理右边子序列

#include<bits/stdc++.h>
using namespace std;
void quickSort(int* arr,int low,int high);
int  main()
{
    int n,a[50];
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i];
    quickSort(a,0,n-1);
    for(int i = 0; i < n; i++)
        cout << a[i] << " ";
    return 0;
}
void quickSort(int* arr,int low,int high)
{
    int i = low, j = high;
    if(i >= j)
        return;
    int pivot = arr[i];
    while(i < j && arr[j] >= pivot)
        j--;
    arr[i] = arr[j];
    while(i < j && arr[i] <= pivot)
        i++;
    arr[j] = arr[i];
    arr[i] = pivot;
    quickSort(arr,low,i-1);
    quickSort(arr,i+1,high);
}

发布了3 篇原创文章 · 获赞 3 · 访问量 193

猜你喜欢

转载自blog.csdn.net/qq_39381361/article/details/105146230