快速排序的时间复杂度为O(nlogn)
基本思想是:(1)先取一个基准值temp(一般是数组第一个数)
(2)与数组中其他数值进行比较,比temp大的放在基准值的右边,小于等于它的放在左边,此时temp已经在它排序后的正确位置
(3)在左右俩部分依次进行(2)中的操作,直到每一部分都只剩一个数字
代码如下:
/**
* Created by 亮大王 on 2017/8/31.
*/
import java.util.Arrays;
public class no3 {
public static void main(String[] args) {
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
System.out.println(Arrays.toString(a));
no3 nn =new no3();
nn.quickSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
public int partition(int[] a, int low, int high) {
int temp = a[low];
while (low < high) {
while (low < high && a[high] > temp)
high--;
if (low < high)
a[low++] = a[high];
while (low < high && a[low] <= temp)
low++;
if (low < high)
a[high--] = a[low];
}
a[low] = temp;
return low;
}
public void quickSort(int a[], int low, int high) {
if (low >= high) {
return;
}
int current = partition(a, low, high);
quickSort(a, low, current - 1);
quickSort(a, current + 1, high);
}
}