Java算法-快速排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013034793/article/details/78052964


通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的数据均比关键字小,而另一部分记录的数据均比关键字大,则分别对这两部分继续进行排序,直到整个序列有序。


把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。

这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。


算法代码:

1.查找中轴(最低位作为中轴)所在位置

	public static int getMiddle(int[] numbers,int low,int high){
		int temp = numbers[low];
		while (low<high) {
			while(low<high && numbers[high] > temp){
				high--;
			}
			numbers[low]=numbers[high];
			while (low<high && numbers[low] < temp) {
				low++;
			}
			numbers[high]=numbers[low];
			
		}
		numbers[low]=temp;
		return low;
	}


2、 递归形式的分治排序算法:

	public static void quickSort(int[] numbers,int low,int high){
		if (low<high) {
			int middle = getMiddle(numbers, low, high);
			quickSort(numbers, low, middle-1);
			quickSort(numbers, middle-1, high);
		}
	}


3..快速排序提供方法调用

	public static void quick(int[] numbers){
		if (numbers.length > 0) {
			quickSort(numbers, 0, numbers.length-1);
		}
	}



猜你喜欢

转载自blog.csdn.net/u013034793/article/details/78052964