Java排序七:快排

public class TestDemo {
	public static void main(String[] args) {
		int[] arr = new int[10];
		Random random = new Random();
		for (int i = 0; i < arr.length; i++) {
			arr[i] = random.nextInt(100);
		}
		display(arr);
		sort(arr, 0, arr.length - 1);
		display(arr);
	}

	public static void sort(int[] arr, int left, int right) {
		if (left < right) {
			int partition = getPartition(arr, left, right);
			sort(arr, left, partition - 1);
			sort(arr, partition + 1, right);
		}
	}

	private static int getPartition(int[] arr, int left, int right) {
		int temp = arr[left];
		while (left < right) {
			while (arr[right] >= temp && left < right) {
				right--;
			}
			if (left < right) {
				arr[left++] = arr[right];
			}
			while (arr[left] <= temp && left < right) {
				left++;
			}
			if (left < right) {
				arr[right--] = arr[left];
			}
		}
		arr[left] = temp;
		return left;
	}

	private static void swap(int[] arr, int i, int j) {
		if (i == j) {
			return;
		}
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}

	private static void display(int[] arr) {
		for (int i = 0, len = arr.length; i < len; i++) {
			System.out.print(arr[i] + "  ");
		}
		System.out.println();
	}
}

你可能感兴趣的:(Java排序七:快排)