快速排序
codeblocks 17 通过
Code
// @ChenYe 2018/12/05
#include <iostream>
#define MAXSIZE 1000
using namespace std;
int len; // 全局长度变量ing namespace std;
int Count = 0; // 计数
void Swap(int a[], int low, int high)
{
int temp;
temp = a[low];
a[low] = a[high];
a[high] = temp;
}
int Partition(int a[], int low, int high)
{// 计算基准点,并将小于基准点的元素放在基准点左边,大于的放右边
int point;
point = a[low];
while( low < high )
{// while循环一遍a数组,以piont为基准值分成两边
while( low < high && a[high] >= point )// 比较右边
{
high--;Count++;
}// 出whille的时候说明需要移动了
Swap(a, low, high);
while( low < high && a[low] <= point )// 比较左边
{
low++;Count++;
}// 出whille的时候说明需要移动了
Swap(a, low, high);
}
return low;
}
void QSort(int k[], int low, int high)
{// 出递归条件low == high
int point;
if( low < high )
{
point = Partition(k, low, high); // 计算基准点的函数(关键)
// 递归基准点左右
QSort(k, low, point-1);
QSort(k, point+1, high);
}
}
void QuickSort(int a[])
{
QSort(a, 0, len-1);
}
int main()
{
int num[MAXSIZE];
int n,i, key;
// 输入
for(n=0; n<MAXSIZE; n++) // 从下表0开始
{
cin>>key;
if(key==0)
break;
num[n] = key;
}
len = n;
// 快速排序
QuickSort(num);
// output
for(i=0; i<n; i++)
{
cout<<num[i]<<" ";
}
cout<<"\nsum up to"<<Count<<endl;
return 0;
}
/*
test data:
输入:
1 9 8 5 7 6 4 3 2 0
输出:
1 2 3 4 5 6 7 8 9
*/
版权声明:本文为qq_41420747原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。