快速排序

54 阅读1分钟
public class QuickSort 
{
	public static void main(String args[])
	{
		int a[] = {10,5,10,2};
		System.out.println("this is quciksort:");
		QuickSort(a, 0, a.length - 1);
		output(a);
	}
	public static void output(int a[])//输出
	{
		int i;
		for(i = 0; i < a.length; i++)
		{
			System.out.print(a[i] + " ");
		}
		System.out.println();
	}
	public static void QuickSort(int a[], int low, int high)
	{
		if(low >= high)
		{
			return;
		}
		int l = low;
		int h = high;
		int now = a[low];//设置哨兵
		while(l < h)
		{
			while(l < h && a[h] >= now)//右比较
			{
				h--;
			}
			while(l < h && a[l] <= now)//左比较
			{
				l++;
			}
			if(l < h)//交换
			{
				int temp = a[h];
				a[h] = a[l];
				a[l] = temp;
			} 
		}
		int temp = a[l];//换最后的一个值
		a[l] = now;
		a[low] = temp;
		QuickSort(a, low, l - 1);//左递归
		QuickSort(a, h + 1, high);//右	
	}
}

\