[Data structure and algorithm] Detailed and simple sorting (bubble sorting, selection sorting, insertion sorting) complete ideas, and use code to encapsulate the sorting function

This series of articles [Data Structure and Algorithm] All the complete code has been uploaded to github , and those who want the complete code can go there and get it directly. If possible, please click on Star ~ Put a jump link below

In the previous article, I have already talked about the data structure that the front end needs to understand , and we have all encapsulated it. Now we are going to explain the sorting algorithm part . The sorting algorithm, as the name suggests, is to arrange a bunch of messy data in an orderly manner according to certain rules.

When explaining the sorting algorithm, it is roughly divided into two categories, as shown below

Insert picture description here
This article first introduces the realization of three simple sorting ideas and the realization of the code

Insert picture description here

Public number: Lpyexplore's programming hut.
Follow me and update the front-end interview questions from time to time.
There are more e-books , interview questions , data structures and algorithm codes waiting for you to get

1. Big O notation

Big O notation is a representation method that roughly represents the time complexity of an algorithm, where the time complexity of the algorithm represents the number of basic operations required by the code during the execution of the algorithm.

Q: Suppose there are five individuals, respectively A, B, C, D, E, their height, respectively 165, 178, 150, 180, 200, you find the highest man, and record the number of comparisons.

Let’s talk about a particularly simple and easy-to-understand algorithm to understand Big O notation

A: Let's use Awith Bthe comparison, was Bmore than Ahigh; then we will use Bwith the Ccomparison, was Cmore than Blow; continue with Bthe Dcomparison, was Dmore than Bhigh; and finally Dwith Ethe comparison, was Emore than Dhigh. Therefore, the final results Eare the highest of the five men have, and we have to remember the number of comparisons for the next 4 times.

Then the same this way, the number is now set n, then we have to compare the number of times it can take up to n - 1times, then we can be the time complexity of this algorithm is toO(n)

Why is O(n)it? Because this method of representation is actually a vague statistical method, we must follow the following principles :

  1. Only the highest number of code runs
  2. All the constants of the addition term are replaced by 1
  3. The constant of the highest order term is replaced by 1

Therefore, when comparing the number of times n - 1when we want to just take the highest degree term, and the constant term becomes the highest-order term 1, so use it as a big O notationO(n)

There are several other common big O notation as follows:

symbol name
O (1) constant
O(log(n)) logarithm
O (n) Linear
O (nlog (n)) Linear and logarithmic product
O (n²) square
O ( 2 n 2 ^ n2n) index

After each sorting algorithm, we will simply judge their time complexity, and use the big O notation to represent

Two, bubble sort

Bubble sort is one of the simplest and rude sorting algorithms. Its sorting method is the same as its name, and data pops up one by one.

Let's take a look at the specific implementation process (the sorting process is from small to large), and look directly at a moving picture

Insert picture description here
The main idea is actually to start from the left and compare the sizes of two adjacent elements in turn. If the number on the left is greater than the number on the right, exchange, so that after comparing all adjacent elements, the number on the right is one of them. The largest number.

Then continue to start from the leftmost side, compare each adjacent element in turn, and determine whether it is necessary to exchange positions, but the difference from the first pass is that the rightmost number does not need to be compared because it is already the largest. Therefore, the second number from right to left after the second pass is the second largest number.

By analogy, the data can be arranged in ascending order

Let's take a look at how to encapsulate the bubble sort function

function bubbleSort(arr) {
    
    

	// 封装一个交换函数,便于之后调用
	function exchange(v1, v2) {
    
    
		let temp = arr[v1]
		arr[v1] = arr[v2]
		arr[v2] = temp
	}
	
	// 获取传入数组的长度
	let length = arr.length
	
	// 1. 设置每次遍历的长度,每遍历一次,长度 - 1
	for(let i = length - 1; i >= 0; i --) {
    
    
		// 2. 从最左边的数开始,依次比较相邻元素
		for(let j = 0; j < i; j ++) {
    
    
			// 3. 如果左边的数大于右边的数,则交换一下两个元素
			if(arr[j] > arr[j + 1]) {
    
    
				exchange(j, j + 1)
			}
		}
	}
	
	// 返回排序后的数组
	return arr
}

Let's simply test whether the method is correct

let arr = [45, 66, 1, 19, 34, 80, 2]

console.log(bubbleSort(arr));
// 打印结果:[1, 2, 19, 34, 45, 66, 80]

Next, talk about the bubble sort of the number of comparisons and the number of exchanges on how Big O notation used to represent.

Assuming that there are 4 numbers in an array, we need to compare 3 times for the first traversal, and then find a maximum value; for the second traversal, we only need to compare 3 of them, and only need to compare 2 times. The second largest value; the third traversal only needs to compare the remaining two numbers, and only needs to compare once, and the array is sorted. If you don’t understand, you can look at the animation above

Compare the number of cases of a total of 3 + 2 + 1 = 6times. Then extended to the general case, there is an array of nelements, then the number of comparisons required a total (n-1) + (n-2) + …… + 2 + 1 = n*(n-1)/2, represents the rule of law in accordance with the big O, we find the highest-order term is n²/2, its constant term is set to 1, it is , therefore bubbling The number of comparisons for sorting is expressed in Big OO(n²)

Let's take a look at how the number of exchanges of bubble sort is represented by big O notation. Obviously, we don’t know exactly how many times to exchange, so we assume that every two comparisons need to be exchanged, the total number of exchanges is n*(n-1)/4. According to the rules of big-O notation, we can know that the number of exchanges is big O Notation is alsoO(n²)

to sum up:

  1. Number of comparisons of bubble sort: O(n²)
  2. Number of exchanges for bubble sort: O(n²)

Three, select sort

Selective sorting is very similar to bubble sorting. The only difference is that each time the selection sorting is traversed, the elements are compared, and the index of the maximum or minimum value is stored in a variable. After all comparisons are completed, the index on the The elements are exchanged. Simply put, the selection sort is exchanged once per traversal, and the bubble sort needs to be exchanged multiple times per traversal, so the selection sort is generally more efficient than the bubble sort.

Similarly, let's take a look at the animation display of the selection sort (sorted from small to large):

Insert picture description here
Let's take a look at the code package for selecting sort

function selectionSort(arr) {
    
    
    // 封装交换元素的函数,方便后面调用
    function exchange(v1, v2) {
    
    
        let temp = arr[v1]
        arr[v1] = arr[v2]
        arr[v2] = temp
    }
	
	// 获取传入数组的长度
    let length = arr.length
	
	// 1. 设定遍历的范围
	for(let i = 0; i < length - 1; i ++) {
    
    
		// 2. 先将遍历的起始索引设为最小值的索引
		let min = i
		// 3. 从索引为min的后一个值开始遍历全部元素
		for(let j = min; j < length; j ++) {
    
    
			// 3.1 将每个遍历到的元素与arr[min]比较
			if(arr[min] > arr[j]) {
    
    
				min = j
			}
		}
		// 4. 将得到的最小值的索引min上的元素与我们初始遍历的位置上的元素交换
		exchange(min, i)
	}

	// 返回排序后的数组
	return arr
}

Let's test whether the method is correct

let arr = [45, 66, 1, 19, 34, 80, 2]

console.log(selectionSort(arr));
// 打印结果:[1, 2, 19, 34, 45, 66, 80]

After understanding the difference between selection sort and bubble sort, we should be able to clearly know that the number of comparisons of selection sort is the same as that of bubble sort, so the number of comparisons of selection sort is expressed in big O notationO(n²)

Each time the selection sort traverses the array, data only needs to be exchanged once, so the number of exchanges is expressed in big O notation asO(n)

to sum up:

  1. Number of comparisons for selection sort: O(n²)
  2. Number of exchanges for selection sort: O(n)

Four, insertion sort

Insertion sorting is a sorting algorithm that compares a specified element with an ordered area element and exchanges positions.

Let’s give a simple example. Suppose there is such an unordered array.

Insert picture description here
First of all, we regard the element with index 0 as a region. The region is ordered. Because there is only one element, it is one element in any order, so it is considered to be ordered.

We then take the first element of the ordered regions on the right, i.e., the index of the element 1 67, the variable stored tempin. And from the start of the rightmost ordered regions, the variable elements sequentially tempelements in 67comparison, if greater than 67, then moves to the right position of a frame; if less than 67, there is no need to continue to traverse because this region is ordered of.

FIG movable first traversal:
Insert picture description here
in this case the ordered region 索引0 ~ 索引1this section, we will index the element 2 is taken out, in comparison with the elements ordered regions

The animation for the second traversal:

Insert picture description here
At this time, the area was ordered 索引0 ~ 索引2this section, we will remove the index element 3, the comparison with the elements ordered area

The animation of the third traversal:

Insert picture description here
At this time, the area was ordered 索引0 ~ 索引3this section, we will remove the element index of 4, compare with the elements ordered area

The animation of the fourth traversal:

Insert picture description here
At this time, the entire array is an ordered area, which is a complete insertion sort

Next we will encapsulate a function for insertion sort

function insertionSort(arr) {
    
    
	// 获取传入数组的长度
    let length = arr.length
	
	// 1. 从索引为1的元素开始向后遍历数组
	for(let i = 1; i < length; i ++) {
    
    
		// 2. 取出有序区域右边第一个元素
		let temp = arr[i]
		let j = i
		// 3. 从右往左将有序区域内的元素与temp比较
		while(arr[j - 1] > temp && j > 0) {
    
    
			arr[j] = arr[j - 1]
			j --
		}
		// 4. 将temp插入到合适的位置
		arr[j] = temp
	}
	
	// 返回排序后的数组
	return arr
}

Let's test whether the function is correct

let arr = [45, 66, 1, 19, 34, 80, 2]

console.log(insertionSort(arr));
// 打印结果:[1, 2, 19, 34, 45, 66, 80]

Each time insertion sort is traversed, the number of comparisons and the number of element moves are uncertain, so we consider the worst case.

The first traversal: the number of comparisons is 1, the number of element moves is 1; the
second traversal: the number of comparisons is 2, the number of element moves is 2;
...
Nth traversal: the number of comparisons is N, the number of element moves is N;

Therefore, the number of comparisons for insertion sort is 1 + 2 + …… + n, and the number of moves of elements is the same as the number of comparisons. Then we take an average value, that is (n² - n)/4, expressed in Big O notation asO(n²)

to sum up:

  1. The number of comparisons for insertion sort: O(n²)
  2. Number of element movement for insertion sort: O(n²)

Six, concluding remarks

The simple sorting in the sorting algorithm is over. The next article will explain three advanced sorting algorithms : Hill sorting, merge sorting, and quick sorting.

You can follow me, and I will continue to update other data structure and algorithm articles for everyone to learn from, and I will put these articles in the [Data Structure and Algorithm] column for everyone to learn and use.

Then you can pay attention to my WeChat official account : Lpyexplore's programming hut . After the article in this column is finished, I will put the notes of each data structure and algorithm on the official account , and you can go there to get it.

Or you can go to my github to get the complete code , welcome everyone to order Star

I’m Lpyexplore. It’s not easy to create. If you like it, add attention, click a favorite, give a like~

Guess you like

Origin blog.csdn.net/l_ppp/article/details/108498581