zoukankan      html  css  js  c++  java
  • java快速排序

    package com.sort;

    public class QuickSort {
    // 快速排序采用了分治策略。就是在一个数组中取一个基准数字,把小的数放基准的左边,大的数放基准的右边。
    // 基准左边和右边分别是新的序列。在新的序列中再取一个基准数字,小的放左边,大的放右边。
    // 这个里面用到的递归。我们需要三个参数,一个是数组,另外两个是序列的边界
    public static void sort(int[] arr, int left, int right) {
    // 序列里最少要有两个数
    if (right > left) {
    // i是下标值,左边的值比arr[i]小,右边的值比arr[i]大
    int i = partion(arr, left, right);
    // 左边和右边的序列再用分治法排列一下,因为用了递归,所以最小的程度是只有序列里只有两个数
    sort(arr, left, i - 1);
    sort(arr, i
    + 1, right);
    }
    }

    // 这个方法的功能就是以arr[left]为基准,把arr[left]到arr[right]之间的数字,大的放右边,小的放左边
    public static int partion(int[] arr, int i, int j) {
    int pivotValue = arr[i];
    // 每次最多执行一次i++,或者j--,这样总有i=j的时候
    while (i != j) {
    // 如果arr[i]==arr[j],那么i和j上的值也会换来换去,但是由于i和j值都没有改变,因此进行了一个死循环,因此必须有一个值做出让步
    if (arr[i] == arr[j]) {
    i
    ++;
    }
    else if (arr[i] < pivotValue) {
    i
    ++;
    }
    else if (arr[j] > pivotValue) {
    j
    --;
    }
    else {
    // else的情况是i上的值大于等于基准,或者j上的值小于等于基准。
    // 为什么我们要调换i和j呢,因为基准数必然是i或者j上的值。
    swap(arr, i, j);
    }
    }
    return i;
    }

    public static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i]
    = arr[j];
    arr[j]
    = temp;
    }

    public static void printArr(int[] arr) {
    for (int index : arr) {
    System.out.print(index
    + " ");
    }
    System.out.println();
    }

    public static void main(String[] args) {
    // int[] arr = { 49, 38, 65, 97, 76, 13, 27 };
    // int[] arr = { 49, 49, 65, 97, 76, 13, 27 };
    int[] arr = { 27, 27, 65, 97, 49, 27, 27 };
    sort(arr,
    0, arr.length - 1);
    printArr(arr);
    }
    }

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    微信小程序TodoList
    C语言88案例-找出数列中的最大值和最小值
    C语言88案例-使用指针的指针输出字符串
  • 原文地址:https://www.cnblogs.com/qinying/p/2172536.html
Copyright © 2011-2022 走看看