排序算法之快速排序【java实现】

快速排序是最常用的排序算法之一,它的平均时间复杂度是O(nlogn),但是它是一个不稳定的算法。

步骤:

我们要找到一个基值,将小于基值的放在它的左边,大于它的放在它的右边。基值我们直接用数组最左边的值就行。每次排序会把基值放在正确的位置上,在根据这个值把数组分成左右两部分,在进行递归处理。

(很多同学刚接触的时候会对这个基值有一定的误解,认为这个基值是数组的中间值,必须要选择arr.length/2,其实这个值是随便找的,每一次排序会把这个基值放在正确的排序位置上)

package zhgyu.sort;
/**
 * 快速排序
 * @author zhgyu
 *
 */
public class QuickSort {

	static final int SIZE = 10;
	
	
	public static void quickSort(int[] arr,int low,int high) {
		if(low < high) {
			int pivot = partition(arr,low, high);
			quickSort(arr, low, pivot-1);
			quickSort(arr, pivot+1, high);
		}
	}
	
	
	public static int partition(int[] arr, int low, int high) {
		
		int pivot = arr[low];
		while(low < high) {
			while(low < high && pivot <= arr[high])
				high--;
			arr[low] = arr[high];
			while(low < high && pivot >= arr[low])
				low++;
			arr[high] = arr[low];
		}
		
		arr[low] = pivot;
		return low;
	}
	
	
	public static void main(String[] args) {
			
		int[] arr = new int[SIZE];
		int i;
			
		for(i = 0; i < SIZE; i ++) {
			arr[i] = (int)(Math.random()*(100 + 1));
		}
		//排序前的数组
		System.out.print("排序前的数组:"+"\t");
		for(i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
				
		}
		System.out.println();
		
		quickSort(arr, 0, SIZE - 1);
			
		//输出数组arr
		System.out.print("排序后的数组:"+"\t");
		for(i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
		}
		System.out.println();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40702130/article/details/84289154