当前位置:网站首页>Quick sort summary
Quick sort summary
2022-07-05 05:08:00 【ximen502_】
The content and code of the article come from 《 Comics algorithm 》 And data structure textbook . Now let's practice coding .
1. Bilateral circular law
/** * Bilateral circular law , Compare and exchange data from the left and right ends to the middle Recursive implementation */
void quickSortV1(int[] arr, int start, int end) {
// Recursion end condition
if (start >= end) {
return;
}
// Get the benchmark element pivot Location
int pivotIndex = partitionV1(arr, start, end);
// According to the reference elements , Recursion in two parts
quickSortV1(arr, start, pivotIndex - 1);
quickSortV1(arr, pivotIndex + 1, end);
}
/** * A round of comparison and Exchange divide and conquer * * @param arr * @param start * @param end * @return */
private int partitionV1(int[] arr, int start, int end) {
int pivot = arr[start];
int left = start;
int right = end;
while (left != right) {
// control right Pointer compare and move left
while (left < right && arr[right] > pivot) {
right--;
}
// control left Pointer compare and move left
while (left < right && arr[left] <= pivot) {
left++;
}
// In exchange for left,right Pointing elements
if (left < right) {
int p = arr[left];
arr[left] = arr[right];
arr[right] = p;
}
}
// pivot Exchange with pointer coincidence point
arr[start] = arr[left];
arr[left] = pivot;
return left;
}
@Test
public void fun1() {
// int[] arr=new int[]{4,4,6,5,3,2,8,1};
int[] arr = new int[] {
49, 38, 65, 97, 76, 13, 27, 49 };
quickSortV1(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
2. Unilateral circulation method
/** * Unilateral circulation method , * 1. Set up a mark The pointer , Say less than pivot The boundary of the data area * 2. Traverse from left to right and pivot Compare , If greater than or equal to pivot, Keep going backwards * 3. If it is less than , be mark Move back one position , And less than pivot The positions of elements are exchanged * 4. Until the end of a round of traversal , The final will be mark Location elements and pivot Location element exchange location . * * */
void quickSortV2(int[] arr, int start, int end) {
// Recursion end condition
if (start >= end) {
return;
}
// Get the benchmark element pivot Location
int pivotIndex = partitionV2(arr, start, end);
// According to the reference elements , Recursion in two parts
quickSortV2(arr, start, pivotIndex - 1);
quickSortV2(arr, pivotIndex + 1, end);
}
/** * Divide and conquer divide and conquer * * @param arr * @param start * @param end * @return */
private int partitionV2(int[] arr, int start, int end) {
// Take the first position element as the reference element pivot
int pivot = arr[start];
int mark = start;
for (int i = start + 1; i <= end; i++) {
if (arr[i] < pivot) {
mark++;
int p = arr[mark];
arr[mark] = arr[i];
arr[i] = p;
}
}
arr[start] = arr[mark];
arr[mark] = pivot;
return mark;
}
@Test
public void fun2() {
int[] arr = new int[] {
49, 38, 65, 97, 76, 13, 27, 49 };
quickSortV2(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
3. Non recursive implementation
/** * Non recursive implementation ( Most recursive logic , Can be replaced by stack ) * * @param arr * @param start * @param end */
void quickSortV3(int[] arr, int start, int end) {
Stack<Map<String, Integer>> stack = new Stack<>();
Map<String, Integer> root = new HashMap<String, Integer>();
root.put("start", start);
root.put("end", end);
stack.push(root);
// End the loop when the stack is empty
while (!stack.isEmpty()) {
Map<String, Integer> item = stack.pop();
int pivotIndex = partitionV3(arr, item.get("start"), item.get("end"));
// It is divided into 2 part , Put the start and end of each part on the stack
if (item.get("start") < pivotIndex - 1) {
Map<String, Integer> left = new HashMap<>();
left.put("start", item.get("start"));
left.put("end", pivotIndex - 1);
stack.push(left);
}
if (pivotIndex + 1 < item.get("end")) {
Map<String, Integer> right = new HashMap<>();
right.put("start", pivotIndex + 1);
right.put("end", item.get("end"));
stack.push(right);
}
}
}
private int partitionV3(int[] arr, int start, int end) {
int pivot = arr[start];
int mark = start;
for (int i = start + 1; i <= end; i++) {
if (arr[i] < pivot) {
mark++;
int p = arr[mark];
arr[mark] = arr[i];
arr[i] = p;
}
}
arr[start] = arr[mark];
arr[mark] = pivot;
return mark;
}
@Test
public void fun3() {
int[] arr = new int[] {
49, 38, 65, 97, 76, 13, 27, 49 };
quickSortV3(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
The algorithm of data structure textbook is transformed into C Language
#include<iostream>
using namespace std;
/* data structure (C Language version ) YanWeiMin , Wei-min wu The quick sort algorithm is converted into code */
int Partition(int arr[], int low, int high){
int pivot = arr[low];// The first record is pivot
while(low<high){
while(low<high && arr[high]>=pivot){
--high;
}
arr[low]=arr[high];
while(low<high && arr[low]<=pivot){
++low;
}
arr[high]=arr[low];
}
arr[low]=pivot;
return low;
}
void Qsort(int arr[], int low, int high){
if(low < high){
int pivotLoc = Partition(arr, low, high);
Qsort(arr, low, pivotLoc-1);
Qsort(arr, pivotLoc+1,high);
}
}
int main(int argc, char* argv[]) {
int arr[]={
49,38,65,97,76,13,27,49};
Qsort(arr,0,7);
for(int i=0;i<8;i++){
cout<<arr[i]<<",";
}
return 0;
}
The division and treatment process is shown in the following figure :
summary : The average time complexity of quicksort is O(nlogn). There is a slight difference between the fast sorting algorithm of cartoon algorithm and that of data structure textbook , Mainly reflected in the way of data element exchange . For benchmark data pivot The choice of , The first element of the array is selected by default in the code , But if the initial record sequence is ordered by keywords or basically ordered , Fast sorting will degenerate into bubble sorting , Its time complexity is O(n2), For improvement , The pivot record is usually selected according to the rule of choosing the middle of the three pivot, That is, compare the first , the last one , The size of the middle element , Take the middle as pivot; The comic algorithm also mentions the random selection of an element as the benchmark element pivot, However, there is still a very small chance to choose the maximum or minimum value of the sequence , Affect the effect of partition .
In fact, after every round of data exchange , return pivot The current position , according to pivot Position divides an array into 2 Subarray , Continue to recursively process the subarray , Until the length of the subarray becomes 1.
边栏推荐
- Unity writes timetables (without UI)
- Unity ugui source code graphic
- Cocos2dx screen adaptation
- Cocos2dx Lua registers the touch event and detects whether the click coordinates are within the specified area
- PostgreSQL surpasses mysql, and the salary of "the best programming language in the world" is low
- 669. 修剪二叉搜索树 ●●
- LeetCode之單詞搜索(回溯法求解)
- China needle coke industry development research and investment value report (2022 Edition)
- PR first time
- Understand encodefloatrgba and decodefloatrgba
猜你喜欢
stm32Cubemx(8):RTC和RTC唤醒中断
Unity get component
Redis has four methods for checking big keys, which are necessary for optimization
Embedded database development programming (V) -- DQL
Understand encodefloatrgba and decodefloatrgba
3dsmax snaps to frozen objects
JVM call not used once in ten years
[paper notes] multi goal reinforcement learning: challenging robotics environments and request for research
Page countdown
Use assimp library to read MTL file data
随机推荐
2022/7/1學習總結
Listview is added and deleted at the index
django连接数据库报错,这是什么原因
Do a small pressure test with JMeter tool
Pdf to DWG in CAD
Rip notes [rip three timers, the role of horizontal segmentation, rip automatic summary, and the role of network]
MD5绕过
AutoCAD - lengthening
AutoCAD - command repetition, undo and redo
PostgreSQL surpasses mysql, and the salary of "the best programming language in the world" is low
This article is good
win10虚拟机集群优化方案
669. 修剪二叉搜索树 ●●
Simple modal box
54. 螺旋矩阵 & 59. 螺旋矩阵 II ●●
Cocos progress bar progresstimer
AutoCAD - set layer
中国艾草行业研究与投资前景预测报告(2022版)
UE fantasy engine, project structure
Redis has four methods for checking big keys, which are necessary for optimization