java快排

public class QuickSort {

	// 简化使用方法 传入一个参数即可
	public static void quickSortHelp(int arr[]) {
		quickSort(arr, 0, arr.length - 1);
	}

	public static void quickSort(int arr[], int low, int high) {
		if (low < high) {
			// 获取排序后最中间那个元素的角标
			int partition = partition(arr, low, high);
			// 递归 把这个元素左边的所有数看作一个数组继续进行快排
			quickSort(arr, low, partition - 1);
			// 递归 把这个元素右边的所有数看作一个数组继续进行快排
			quickSort(arr, partition + 1, high);

		}
	}

	// 对数组进行排序
	public static int partition(int arr[], int low, int high) {
		// 当low=high时说明排序已经进行完了
		while (low < high) {
			// 寻找low右边比arr[low]小的值
			while (arr[high] >= arr[low] && high > low) {
				high--;
			}
			// 把找到的值都放到low的左边
			swap(arr, low, high);
			// 寻找high左边比arr[high]大的值
			while (arr[low] <= arr[high] && low < high) {
				low++;
			}
			// 把找到的值都放到high的右边
			swap(arr, low, high);
		}
		// 这个low就是排序后最中间元素的角标
		return low;

	}

	// 把两个数的位置调换
	public static void swap(int arr[], int low, int high) {
		int temp = arr[low];
		arr[low] = arr[high];
		arr[high] = temp;
	}

	public static void main(String[] args) {

		int[] arr = { 2, 8, 5, 6, 10, 5, 4, 66, 11, 15, 3, 18, 7 };
		quickSortHelp(arr);
		for (int i : arr) {
			System.out.print(i + " ");
		}

	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值