package com.demo; public class Demo { public static void main(String[] args) { int[] intArray = {12, 11, 45, 6, 8, 43, 40, 57, 3, 8,34}; System.out.println("Befor sorting: "); for (int i = 0; i < intArray.length; i++) { System.out.print(intArray[i] + " "); } System.out.println(); System.out.println("After sorting: "); int[] b = quickSort(intArray, 0, intArray.length - 1); for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } } public static int getMiddle(int[] array, int left, int right){ int temp; //进行一趟快速排序,返回中心点位置 int mid = array[left]; while(left < right){ while(left < right && array[right] >= mid) right--; /** * 将比中心点小的数据移到左边 */ temp = array[right]; array[right] = array[left]; array[left] = temp; while(left < right && array[left] <= mid) left++; /** * 将比中心点大的数据移动到右边 */ temp = array[right]; array[right] = array[left]; array[left] = temp; } array[left] = mid; //中心移到正确位置 return left; //返回中心点 } public static int[] quickSort(int[] array, int left, int right){ if(left < right ){ int mid = getMiddle(array, left, right); quickSort(array, left, mid - 1); quickSort(array, mid + 1, right); } return array; } }
最坏情况时间复杂度O(n2),最好情况时间复杂度O(nlog2n).