Home Java javaTutorial Graphical explanation of how to implement quickSort quick sorting algorithm in Java

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

Jan 19, 2017 am 09:13 AM

Compared with algorithms such as bubble sorting and selection sorting, the specific algorithm principle and implementation of quick sorting are somewhat difficult. In order to better understand quick sort, we still describe the algorithm principle of quick sort in detail in the form of examples. In the previous sorting algorithm, we took the height sorting problem of 5 athletes as an example to explain. In order to better reflect the characteristics of quick sorting, here we add 3 additional athletes. The details of the eight athletes in the example and their height information are as follows (F, G, and H are new athletes): A(181), B(169), C(187), D(172), E(163), F(191), G(189), H(182)

In the previous sorting algorithm, these sortings were all completed by the coach. Now that the number of athletes has increased, the coach also wants to take the opportunity to take a rest. , so the coach called two assistants and asked them to sort the heights of the eight athletes from left to right and from low to high using the quick sort method.

According to the algorithm principle of quick sorting method, two assistants stand on both sides of the athlete arrangement, as shown in the figure below

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

First, Assistant 1 starts from Select an athlete from the arrangement (usually the first athlete on the left or the middlemost athlete), here select athlete A (181). Since the sorting is from left to right and from low to high, Assistant 1 needs an athlete whose height is smaller than A(181) (the selected A(181)) as the benchmark for comparison. All comparisons in this round are with Initially selected athlete A (181) comparison):

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

# Let’s continue to refer to the detailed diagram of the first round of quick sorting.

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

Graphical explanation of how to implement quickSort quick sorting algorithm in Java

##When the two assistants were sorting and looking for After meeting during the process, the comparison of the current round is stopped, and the initially selected athlete A (181) is placed in the empty space where the two assistants meet

In quick sorting, when the two assistants meet , this round of sorting is over. At this time, we find that taking the position A(181) where the two athletes meet as the dividing point, those on the left side of the arrangement are all athletes with a height smaller than A(181), and those on the right side of the arrangement are all athletes with a height greater than A(181) athlete. At this time, we will look at the two sortings on the left and right sides of A(181) separately. If we continue to use the sorting methods of the two assistants mentioned above to sort the arrangements on both sides, then after multiple arrangements, finally We can get the sorting results we need.

The above is the entire sorting implementation process of quick sort. Quick sort uses the above sorting rules to divide one arrangement into two arrangements, and two arrangements into four arrangements, until there are no arrangements to separate, and finally we get the sorting result we need.

Now, we still program Java code to use quick sort to sort the heights of the above 8 athletes:

/**
 * 对指定的数组中索引从start到end之间的元素进行快速排序
 * 
 * @param array 指定的数组
 * @param start 需要快速排序的数组索引起点
 * @param end 需要快速排序的数组索引终点
 */
public static final void quickSort(int[] array, int start, int end) {
  // i相当于助手1的位置,j相当于助手2的位置
  int i = start, j = end;
  int pivot = array[i]; // 取第1个元素为基准元素
  int emptyIndex = i; // 表示空位的位置索引,默认为被取出的基准元素的位置
  // 如果需要排序的元素个数不止1个,就进入快速排序(只要i和j不同,就表明至少有2个数组元素需要排序)
  while (i < j) {
    // 助手2开始从右向左一个个地查找小于基准元素的元素
    while (i < j && pivot <= array[j])
      j--;
    if (i < j) {
      // 如果助手2在遇到助手1之前就找到了对应的元素,就将该元素给助手1的"空位",j成了空位
      array[emptyIndex] = array[emptyIndex = j];
    }
     
    // 助手1开始从左向右一个个地查找大于基准元素的元素
    while (i < j && array[i] <= pivot)
      i++;
    if (i < j) {
      // 如果助手1在遇到助手2之前就找到了对应的元素,就将该元素给助手2的"空位",i成了空位
      array[emptyIndex] = array[emptyIndex = i];
    }
  }    
  // 助手1和助手2相遇后会停止循环,将最初取出的基准值给最后的空位
  array[emptyIndex] = pivot;
   
  // =====本轮快速排序完成=====
   
  // 如果分割点i左侧有2个以上的元素,递归调用继续对其进行快速排序
  if (i - start > 1) {
    quickSort(array, 0, i - 1);
  }
  // 如果分割点j右侧有2个以上的元素,递归调用继续对其进行快速排序
  if (end - j > 1) {
    quickSort(array, j + 1, end);
  }
}
 
//主方法
public static void main(String[] args) {
  // =====使用快速排序法对表示8名运动员身高的数组heights进行从低到高的排序=====
  // A(181)、B(169)、C(187)、D(172)、E(163)、F(191)、G(189)、H(182)
  int[] heights = { 181, 169, 187, 172, 163, 191, 189, 182 };
  // 调用快速排序方法
  quickSort(heights, 0, heights.length - 1);
  // 输出排序后的结果
  for (int height : heights) {
    System.out.println(height);
  }
}
Copy after login

The output of the above Java code is as follows:

163
169
172
181
182
187
189
191
Copy after login

Note: Due to local differences in thinking, the code implementation of the above quick sort may have multiple variations. However, no matter what form of variation, the core idea of ​​quick sort does not change.

Another implementation: one-way scanning

There is another version of one-way scanning for quick sorting array splitting. The specific steps are to select the last element in the array as the splitting element, and set the same Two pointers, pointer i points to the position before the first element in the array, and pointer j points to the first element in the array. j scans from front to right, left to right, and increases i by one when it encounters an element that is less than or equal to the split element, and then swaps the elements pointed to by i and j. Finally, swap the element at position i+1 with the split element to complete an array division. The code is implemented as follows:

int partition(int[] a, int lo, int hi) {
  int i = lo - 1, j = lo;
  int v = a[hi];
  while (j < hi) {
    if (a[j] <= v) {
      swap(a, ++i, j);
    }
    j++;
  }
  swap(a, i + 1, hi);
  return i + 1;
}
Copy after login

For more pictures and texts explaining the method of implementing the quickSort quick sorting algorithm in Java, please pay attention to the PHP Chinese website for related articles!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1228
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles