Fast sorting algorithms manuscript version

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sinat_32336967/article/details/98874420

Read a hundred times, its meaning from the see. Sure enough, every review will have a different harvest.

1. sorting process

Quick drain of the detailed process is shown below.
Here Insert Picture Description
Here Insert Picture Description
1,2,3,4 cycle is a cycle that low <high. low == high time to quit.
1 and 3 is then two cycles are used to find a number satisfying the condition.
The first step in the loop condition is low <high && arr [high] > = temp. Less than the number found before the exit temp
cycling conditions of the second step is low <high && arr [low] <= temp. Find the temp was greater than the number of exits.
The third step and the fourth step is the assignment.
The third step is to find the number is less than temp arr [high] assigned to arr [low].
The fourth step is to find the temp is greater than the number of arr [low] is assigned to arr [high].
The end of the last cycle, temp is assigned to arr [low].
At this time, the index returns. Recursion for arr [low] -> arr [ pos-1] and arr [pos + 1] -> arr [high] to fast discharge.

2. Sample Code

package org.jinyuxin.sort.ExchangeSort;

public class QuickSort {
  public static void main(String[] args) {
    int[] arr = {8,5,6,7,4,2,3,1};
    int len = arr.length;
    quickSort(arr, 0,len-1);
    for(int i:arr) {
      System.out.println(i);
    }
  }

  public static void quickSort(int[] arr, int low, int high) {
    if(low < high) {
      int pos = findPosition(arr, low, high);
      //递归对右半边进行快排
      quickSort(arr,low,pos-1);
      //对左半边进行快排
      quickSort(arr,pos+1,high);
    }
  }

  public static int findPosition(int[] arr, int low, int high) {
    //枢纽值
    int temp = arr[low];

    //low等于high的时候退出循环
    while(low < high) {
      //从后向前,直到找到第一个小于temp的数才退出
      while(low< high && arr[high] >= temp){
        high--;
      }
      //找到小于枢纽值的数以后,赋值给arr[low]
      arr[low] = arr[high];

      //从前向后,直到找到第一个大于temp的数才退出
      while(low < high &&arr[low] <= temp) {
        low++;
      }
      //找到大于枢纽值的数以后,赋值给arr[high]
      arr[high] = arr[low];
    }

    //此时将枢纽值赋值给low=high位置
    arr[low] = temp;
    //返回枢纽的最终位置
    return low;
  }
}

3. Sample results

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/sinat_32336967/article/details/98874420