/*!
* @file 快速排序.cpp
* @Date: 2018/01/29 21:15
* @author: sicaolong
* @Contact: sicaolong@163.com
* @brief:
* @TODO:
*/
#include<iostream>
using namespace std;
void QuickSort(int *,int low, int high);
int partation(int *, int low, int high);
int main()
{
int n;
cout << "请输入您要输入的数组的个数:" << endl;
cin >> n;
int *a = new int[n];
cout << "请输入您要输入的数组的数据:" << endl;
for (int i = 0; i < n; i++)
{
cout << "您要输入的第 " << i + 1 << "个数据为:";
cin >> a[i];
}
cout<<endl;
cout << "您输入的数组为:" << endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
cout << "经过快速排序后:" << endl;
QuickSort(a,0, n-1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
delete[]a;
}
void QuickSort(int *a,int low,int high)
{
int postion;//某一个元素所在的位置
if (low < high)
{
postion = partation(a, low, high);
QuickSort(a, low, postion - 1);//左侧部分再快速排序;
QuickSort(a, postion + 1, high);//右侧部分快速排序
}
}
//===============求出某个元素的位置;
int partation(int *a, int low, int high)
{
int key=a[low];//关键值key 为a[0],查找key 所在的位置
while (low<high)
{
while (low < high&& a[high]>key)
high--;
a[low] = a[high];
while (low < high&&a[low] < key)
low++;
a[high] = a[low];
}
a[low] = key;//将key值赋给第 low+1位置上的数据;
return low;//low和high相等
}
快速排序
最新推荐文章于 2024-07-17 10:35:12 发布