快速排序

66 阅读1分钟

Problem Description

对n个整数进行从小到大排序。

Input

第一行输入一个数n(n<=100),第二行是n个整数。

Output

输出n个从小到大排列的数,数字之间用空格隔开。

Sample Input

8

5 2 1 8 6 3 8 2

Sample Output

1 2 2 3 5 6 8 8

程序代码:

#include<stdio.h>
#define N 110
int a[N];
void Quicksort(int left,int right);
int main()
{
	int i,n;
	while(scanf("%d",&n)!=EOF)
	{
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		Quicksort(0,n-1);
		for(i=0;i<n;i++)
			printf("%d ",a[i]);
		printf("\n");
	}
	return 0;
}
void Quicksort(int left,int right)
{
	int i,j,t;
	if(left>right)
		return;
	i=left;
	j=right;
	while(i!=j)
	{
		while(a[j]>=a[left]&&i<j)
			j--;
		while(a[i]<=a[left]&&i<j)
			i++;
		if(i<j)
		{
			t=a[i];
			a[i]=a[j];
			a[j]=t;
		}
	}
	t=a[i];
	a[i]=a[left];
	a[left]=t;
	Quicksort(left,i-1);
	Quicksort(i+1,right);
	return;
}