java 快速排序



public class QuickSort {
	/**
	 * 快速排序
	 * 
	 * @param strDate
	 * @param left
	 * @param right
	 */
	public void quickSort(String[] strDate, int left, int right) {
		String middle, tempDate;
		int i, j;
		i = left;
		j = right;
		middle = strDate[(i + j) / 2];
		do {
			while (strDate[i].compareTo(middle) < 0 && i < right)
				i++; // 找出左边比中间值大的数
			while (strDate[j].compareTo(middle) > 0 && j > left)
				j--; // 找出右边比中间值小的数
			if (i <= j) { // 将左边大的数和右边小的数进行替换
				tempDate = strDate[i];
				strDate[i] = strDate[j];
				strDate[j] = tempDate;
				i++;
				j--;
			}
		} while (i <= j); // 当两者交错时停止

		if (i < right) {
			quickSort(strDate, i, right);// 从
		}
		if (j > left) {
			quickSort(strDate, left, j);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] strVoid = new String[] { "11", "66", "22", "0", "55", "22",
				"10", "32" };
		QuickSort sort = new QuickSort();
		sort.quickSort(strVoid, 0, strVoid.length - 1);
		for (int i = 0; i < strVoid.length; i++) {
			System.out.println(strVoid[i] + " ");
		}
	}

}

Java快速排序的实现可以使用递归的方式来实现。快速排序的基本思想是选取一个基准元素,然后将数组中小于基准元素的数放在左边,大于基准元素的数放在右边,再对左右两个子数组分别进行快速排序,直到整个数组有序为止。 下面是Java快速排序的示例代码: ```java public class QuickSort { public static void quickSort(int[] arr, int left, int right) { if (left < right) { int partitionIndex = partition(arr, left, right); quickSort(arr, left, partitionIndex - 1); quickSort(arr, partitionIndex + 1, right); } } public static int partition(int[] arr, int left, int right) { int pivot = left; int index = pivot + 1; for (int i = index; i <= right; i++) { if (arr[i] < arr[pivot]) { swap(arr, i, index); index++; } } swap(arr, pivot, index - 1); return index - 1; } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = {5, 4, 3, 2, 1}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5] } } ``` 在上面的代码中,`quickSort()` 方法调用了 `partition()` 方法来选取基准元素并进行分区,然后再递归调用 `quickSort()` 方法对左右两个子数组进行快速排序。`partition()` 方法中使用了双指针来确定小于基准元素和大于基准元素的分界点,并将小于基准元素的数放在左边,大于基准元素的数放在右边。最后,将基准元素和分界点的数交换位置,并返回分界点的位置。 运行结果为 `[1, 2, 3, 4, 5]`,说明快速排序算法成功地对数组进行了排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值