Algorithms - sorting (selection sort)

  The selection sorting algorithm is to find the minimum value of the data in the core is placed into the first, second minimum value and then find and put the second, and so on. The following code demonstrates:

 1 let arr = [5, 7, 3, 9, 1]
 2 
 3 function swap(arr, index1, index2) {
 4   var temp = arr[index1]
 5   arr[index1] = arr[index2]
 6   arr[index2] = temp
 7 }
 8 
 9 function changeSort(arr) {
10   for (i = 0; i < arr.length - 1; i++) {
11     let minIndex = i
12     for (j = i; j < arr.length; j++) {
13       if (arr[minIndex] > arr[j]) {
14         minIndex = j
15       }
16     }
17     if (i !== minIndex) {
18       swap(arr, i, minIndex)
19     }
20   }
21 }
22 
23 changeSort(arr)
24 console.log(arr) // 结果 [ 1, 3, 5, 7, 9 ]

 

  

Guess you like

Origin www.cnblogs.com/pcyu/p/11373127.html