js implement sorting algorithms - Bubble Sort (Bubble Sort)

original:

  Ten classic sorting algorithms (moving map presentation)

 

Bubble Sort (Bubble Sort)

  Bubble sort is a simple sorting algorithm. It repeatedly visited the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over. The number of visits to the column work is repeated until there is no longer need to swap, that is to say the number of columns already sorted completed. The origin of the name of the algorithm is because the smaller elements will slowly through the exchange of "float" to the top of the columns.

 

Algorithm Description:

  • Compare adjacent elements. If the first is larger than a second, to exchange their two;
  • We do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair, so that should be the last element is the largest number;
  • Repeating the above steps for all elements, except the last one;
  • Repeat steps 1 to 3 until the sorting is completed.

Dynamic presentation:

 Code:

function bubbleSort(arr) {
  let len = arr.length;
  let temp;
  for (let i = 0; i < len - 1; i++) {
    for (let j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) { 
        temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  // return arr
}


let arr = [3,5,7,1,4,56,12,78,25,0,9,8,42,37];
bubbleSort(arr);

 

Guess you like

Origin www.cnblogs.com/cc-freiheit/p/10942337.html