I. Introduction:

  • Time complexity: O(n²)
  • Space complexity: O(1)
  • Stability: unstable
  • Advantages: Low space complexity and small memory usage
  • Disadvantages: High time complexity, poor execution efficiency, and unstable

Second, core ideas

  • The focus should be on the unsorted part
  • Find the minimum value in unsorted and place it at the end of the sorted list
  • Two cycles. What is the function of each cycle? Naughty here, there are comments in the code, see yourself!!

3. GIF of sorting process

Red: the minimum value in unsorted (this can change, starting as a hypothetical value and then becoming the real minimum value) Green: the value compared to the assumed value Flavin: sorted part Blue: unsorted part

Four, code implementation

Code address: github.com/shubenwumin… I’ll make the comments a little bit more detailed. With my notes and gifs and core ideas, you will be able to understand them quickly.

Functions that swap positions in general:

const changePos = function (arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
}
Copy the code

Specific code:

const selectSort = function (arr) { let length = arr.length; let minIndex; For (let I = 0; for (let I = 0; i < length -1; I ++) {// Assume that the minimum value of the unsorted part is the first element of the unsorted part which is I; minIndex = i; For (let j = I + 1; let j = I + 1; j < length; j++) { if(arr[j] < arr[minIndex]) { minIndex = j; }} // The minimum value is placed at the beginning of the unsorted part or at the end of the sorted part; changePos(arr, i, minIndex); } return arr; }Copy the code