Algorithms & Understanding Quicksort

1. What is quick sort

Quick sorting is an upgraded version of bubble sorting. The essence of sorting is looping, and fast looping means that the loop is fast. Then this quick sorting naturally reduces the number of loops to improve faster loops.

2. Quick sort idea

The main core idea of ​​​​quick sorting is: 选基点、后排序、再分治recursive repetition at the end

2.1 Base selection

arr = [10, 2, 9, 12, 8, 20, 30, 4]
select any number in the arr array as the base point for comparison between the left and right sides, for example, we choose 10

2.2 Postsort

Put the ones less than 10 on the left and those greater than 10 on the right
arr = [2, 9, 8, 4, 10, 20, 30, 12]

2.3 Subdivision

Divide [2, 9, 8, 4] and [20, 30, 12] out, then repeat steps 2.1 and 2.2

3. Code case analysis

function swap(arr, i, j) {
    
    
	let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
function QuickSort(arr, low, high) {
    
    
	if (low >= high) return
	// 1. 选基点 
	let i = low, j = high, pivot = arr[low]
	while(i < j) {
    
    
		// 2. 排序
		while (arr[j] >= pivot && i < j ) {
    
     // 右边大于基点的忽略掉,向前走
			j --
		}
		while (arr[i] <= pivot && i < j ) {
    
     // 左边小于基点的忽略掉,向前走
			i ++
		}
		swap(arr, i, j) // 最后肯定发生右边小于基点,左边大于基点,此时进行交换位置即可
	}
	swap(arr, low, j) // 排序后别完了还要把基准点的值放到左右两边中间,这里的 j 也可以换成 i
	// 3. 分割左右两边,然后重复以上步骤
	QuickSort(arr, low, j - 1)
	QuickSort(arr, j + 1, high)
	return arr
}
let arr = [10, 2, 9, 12, 8, 20, 30, 4]
QuickSort(arr, 0, arr.length - 1)
// 排序后
// arr: [2, 4, 8, 9, 10, 12, 20, 30]

over!

Guess you like

Origin blog.csdn.net/cookcyq__/article/details/124876157