JavaScript selection sort

1. Select sort

  • The numbers following the first digit are compared and swapped if less (greater) than the first digit

  • After the first number is compared, continue to compare the second number with the following number…..

  • Implementation code:

    let arr = [22, 55, 5, 88, 66, 77, 111, 3, 54]; for (var j = 0; j < arr.length - 1; Var I = j++) {var I = j++; i < arr.length; If (arr[j] > arr[I]) {var temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; }}}Copy the code
2. Analyze the code implementation process
  • Simple analysis

    • J = 0 I = 1 ===> (I = j + 1)
    • J = 1 I = 2 ===> (I = j + 1)
    • J = 2 I = 3 ===> (I = j + 1)
    • J = 3 I = 4 ===> (I = j + 1)
    • .
  • Steps:

    • We find that the following code is repeated, with only a few changes.) First: The first number is compared to the following number in turn, and if it is less than the first number, it is swapped

      for (var i = 1; i < arr.length; I++) {/ / is seven times the if (arr [0] > arr [I]) {var temp = arr [0]. arr[0] = arr[i]; arr[i] = temp; }}Copy the code
    • Then: The second number in turn is compared with the following number, if less than the second number, the swap

      for (var i = 2; i < arr.length; I++) {/ / is six times the if (arr [1] > arr [I]) {var temp = arr [1]. arr[1] = arr[i]; arr[i] = temp; }}Copy the code
    • Continue: The third digit is compared to the following digit in turn, and if it is less than the third digit, it is swapped

      for (var i = 3; i < arr.length; I++) {/ / is five times the if (arr [2] > arr [I]) {var temp = arr [2]. arr[2] = arr[i]; arr[i] = temp; }}Copy the code
    • And so on…………..

      \