快速排序java实现

说来惭愧,一直不知道快排,这个主要是一个递归。

public class QSort

{
	public static void main(String[] args)
	{
		quicksort qs = new quicksort();
		int data[] = { 44, 22, 2, 32, 54, 22, 88, 77, 99, 11 };
		qs.data = data;
		qs.sort(0, qs.data.length - 1);
		qs.display();
	}
}

class quicksort {
	public int data[];

	private int partition(int sortArray[], int low, int hight) {
		int key = sortArray[low]; //设置一个Key值,该值在一次分治中一直保持不变
		while (low < hight) {
			while (low < hight && sortArray[hight] >= key) //从后往前,当小于Key的值,把hight赋值给low
				hight--;
			sortArray[low] = sortArray[hight];
			while (low < hight && sortArray[low] <= key)//从前往后,当大于Key的值时,把low赋值给hight
				low++;
			sortArray[hight] = sortArray[low];
		}
		sortArray[low] = key;
		return low;//以此为分治的标记,进行递归。
	}

	public void sort(int low, int hight) {
		if (low < hight) {
			int result = partition(data, low, hight);
			sort(low, result - 1);
			sort(result + 1, hight);
		}
	}

	public void display() {
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i]);
			System.out.print(" ");
		}
	}
}




你可能感兴趣的:(java,String,Class)