Algorithms - sorting (Bubble sort)

  The core bubble sort is to compare two adjacent items, if a second large than the first, then the switch them, so the element is moved up to the correct position, as bubbles emerge feeling.

  As a simple example, there are five numbers 1,5,8,3,2, arranged in order from small to large. code show as below:

 1 let arr = [1, 5, 8, 3, 2]
 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 bubbleSort() {
10   for (let i = 0; i < arr.length - 1; i++) {
11     for (let j = 0; j < arr.length - 1; j++) {
12       if (arr[j] > arr[j + 1]) {
13         swap(arr, j, j + 1)
14       }
 15      }
 16    }
 . 17  }
 18 is  
. 19  bubbleSort (ARR)
 20 is the console.log (ARR) // result is [1, 2, 3, 5, 8]

  To achieve the descending arrangement, simply if (arr [j]> arr [j + 1]) in> to <to.

 

  

Guess you like

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