zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    今日进度
    今日进度
    每周总结
    今日进度
    今日进度
    今日进度
    flask展示Excel
    ubuntu 相关
    python解析xml三种方法【ElementTree】【DOM】【SAX】
    Lambda实现if...elif...else【三元表达式】
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5189845.html
Copyright © 2011-2022 走看看