快速排序
输入格式:
输入第一行给出正整数N(≤105 ),随后一行给出N个(长整型范围内的)整数,其间以空格分隔。
输出格式:
在一行中输出从小到大排序后的结果,数字间以1个空格分隔,行末不得有多余空格。
输入样例:
11
4 981 10 -17 0 -20 29 50 8 43 -5
输出样例:
-20 -17 -5 0 4 8 10 29 43 50 981
参考答案:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int * a;
int length;
}SqList;
int Partition(SqList &L, int low, int high)
{
L.a[0] = L.a[low];
while(low < high)
{
while(L.a[high] > L.a[0] && low < high)
--high;
if(low < high)
L.a[low++] = L.a[high];
while(L.a[low] < L.a[0] && low < high)
++low;
if(low < high)
L.a[high--] = L.a[low];
}
L.a[low] = L.a[0];
return low;
}
void QuickSort(SqList &L, int low, int high)
{
if(low < high)
{
int mid = Partition(L, low, high);
QuickSort(L, low, mid - 1);
QuickSort(L, mid + 1, high);
}
}
int main()
{
SqList L;
scanf("%d", &L.length);
L.a = (int *)malloc(4 * L.length + 4);
for(int i = 1; i <= L.length; i++)
{
scanf("%d", L.a + i);
}
QuickSort(L, 1, L.length);
for(int i = 1; i <= L.length; ++i)
{
if(i-1)printf(" ");
printf("%d", L.a[i]);
}
return 0;
}