#include<iostream>
using namespace std;
int partition(int a[], int low, int high)
{
int pivot = a[low];
while(low < high)
{
while(low < high && a[high] >= pivot)
high--;
a[low] = a[high];
while(low < high && a[low] <= pivot)
low++;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void quicksort(int a[], int low, int high)
{
if(low < high)
{
int pivot_pos = partition(a, low, high);
quicksort(a, low, pivot_pos - 1);
quicksort(a, pivot_pos + 1, high);
}
}
int main()
{
int a[8] = {5, 6, 9, 8, 12, 4, 20, 17};
int n = 8;
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
quicksort(a, 0, n-1);
cout << "after sort" << endl;
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
C++实现快速排序(数组首位作为轴枢)
最新推荐文章于 2024-04-24 22:43:13 发布