js implement sorting algorithms - Selection Sort (Selection Sort)

original:

  Ten classic sorting algorithms (moving map presentation)

 

 

Select the sort (Selection Sort)

  Selection Sort (Selection-sort) is a straightforward sorting algorithm. It works: First, find the minimum unsorted sequence (large) element, sorted sequence stored in the starting position, and then continue to look for the smallest (large) elements from the remaining unsorted element and put it in the sorted sequence the end. And so on, until all the elements are sorted.

 

Algorithm Description:

  • Initial state: disordered region is R [1..n], ordered regions is empty;
  • Run ordering the i (i = 1,2,3 ... n-1) starts, the current ordered regions and disordered regions were R [1..i-1] and R [i..n]. The trip from the current sorting disordered zone - Minimum recording key selected R [K], it will exchange with the first record disordered region R, so that R [1..i] and R [i + 1 ..n] were changed to increase the number of records and the number of records a new order to reduce a new area of ​​disorder;
  • n-1 the end of the trip, the ordered array.

Dynamic presentation:

Code:

function selectionSort(arr) {
  let len = arr.length;
  let temp, minIndex;
  for (let i = 0; i < len - 1; i++) {
    for (let j = i + 1; j < len; j++) {
      minIndex = i;
      if (arr[minIndex] > arr[j]) { // 寻找最小数下标
        minIndex = j;
      }
      if (minIndex !== i) {
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
      }
    }
  }
}


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

 

Guess you like

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