“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”
In a few words
Understand the sorting algorithm of the basic algorithm series – selective sorting
Key points: Time complexity: O(n^2)
Their thinking
Select sort, is by looking for the smallest number and put in the starting position, continuous loop, select the smallest remaining number and put, and so on, until all the data sorted.
The problem solving demo
Ary = [14, 7, 6, 19, 10, 16
Ary [j] <= ary[minIndex] j= I +1 ary[j] <= ary[minIndex] j= I +1 MinIndex = 2 ary[I] = 6,7,14,19,10,16
Round 2: I =1, minIndex=1, continue to compare until the end: minIndex=1 and I =1, 6,7,14,19,10,16
Round 3: I =2, minIndex=2, continue the comparison. Until end: minIndex= 4, after replacement: 6,7,10,19,14,16
Fourth round: I =3, minIndex=3, continue the comparison. Until end: minIndex= 4, after replacement: 6,7,10,14,19,16
Round 5: I =4, minIndex=3, continue the comparison. Until the end: minIndex=5, after replacement: 6,7,10,14,16,19
The final result: 6,7,10,14,16,19
Code implementation
Golang version implementation
func sortXuanze(ary []int) { if len(ary) > 1 { minIndex := 0 for i := 0; i < len(ary)-1; i++ { minIndex = i for j := i + 1; j < len(ary); j++ { if ary[j] <= ary[minIndex] { minIndex = j } } if minIndex ! = i { ary[i], ary[minIndex] = ary[minIndex], ary[i] } } } for _, v := range ary { fmt.Print(v, ",") } }Copy the code
JavaScript version implementation
Function sortXuanze(ary) {if(ary. Length >1) {let minIndex = 0; for (let i = 0; i<ary.length - 1; i++){ minIndex = i; for(let j = i+1; j <ary.length; j++) { if(ary[j] <= ary[minIndex]) { minIndex = j } } if( minIndex ! = i) { let temp = ary[i]; ary[i] = ary[minIndex]; ary[minIndex] = temp; } } } console.log(ary) }Copy the code