Sorting algorithm summary-selection sort

Ideas

In the first round, find the smallest number in the array, and swap the first item with the smallest number.
In the second round, find the smallest number starting from subscript 2, and swap positions with the second term.
…In
the i-th round, find the smallest number starting from the subscript i, and swap positions with the i-th item.

Code

var arr = [9, 3, 1, 5, 4, 6, 2, 8, 7];
function selectSort(arr) {
    
    
  for (var i = 0; i < arr.length -1; i++) {
    
    
    // var firstIndex = i;
    for (var j = i + 1; j < arr.length ; j++) {
    
    
      if (arr[j] < arr[i]) {
    
    
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  }
  console.log(arr);
}
selectSort(arr)

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/113995386