Quick Sort

  • 数组中选择一个元素作为pivot点。
  • 根据pivot元素partition数组
    • 将数组中小于等于pivot的元素移动到pivot的左边。
    • 将数组中大于pivot的元素移动到pivot右边。
    • 在数组的合适位置插入pivot元素。

pivot选取

  • 选取第一个元素
  • 选取最后一个元素(本文实现)
  • 随机选取元素

partition实现

  • 取变量i记录小于或等于pivot元素的最后一个位置
  • 从start位置开始遍历数组
    • 遇到小于等于pivot的元素就和i位置的元素交换位置,增加i的值
    • 否则,忽略当前值,继续循环

Implementation

public void quickSort(int[] arr) {
        quickSort(arr, 0, arr.length - 1);
    }

private void quickSort(int[] arr, int start, int end) {
    if (start >= end)
        return;
    int pivotIndex = partition(arr, start, end);
    quickSort(arr, start, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, end);
}

private int partition(int[] arr, int start, int end) {
    int pivot = arr[end]; // pivot
    int i = start; // Index of smaller element
    for (int j = start; j < end; j++) {
        if (arr[j] <= pivot) { // current element is less than or equal to pivot
            swap(arr, i, j); // swap the two elements
            i++; // increment index of the smaller element
        }
    }
    swap(arr, i, end); // put pivot at correct position
    return i;
}

private void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
posted @ 2016-02-15 03:35  VicHawk  阅读(149)  评论(0编辑  收藏  举报