fork download
  1. // your code goes here
  2.  
  3. // n=5,
  4. // [4, 2, 3, 1, 6]
  5.  
  6. // i=0, (6, 4), (6, 2), (6, 3), (6, 1)
  7.  
  8.  
  9.  
  10. // (0, 1) (1, 2), (2, 3), (3, 4),
  11.  
  12. // i=0, j = 0, 1, 2, 3 < n-1-0
  13. // < n-1-1
  14. // <
  15.  
  16. // function bubbleSort(arr, n) {
  17. // for(let i=0;i<n-1;i++){
  18. // for(let j=0;j<=n-2-i;j++){
  19. // if(arr[j]<arr[j+1]) {
  20. // let tmp = arr[j];
  21. // arr[j] = arr[j+1];
  22. // arr[j+1] = tmp;
  23. // // [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
  24. // }
  25. // }
  26. // }
  27. // return arr;
  28. // }
  29.  
  30. // TC: O(n^2)
  31. // SC: O(1)
  32.  
  33.  
  34. // console.log(bubbleSort([6, 4, 2, 3, 1], 5))
  35.  
  36.  
  37. // SELECTION SORT
  38.  
  39. // n=5, arr = [6, 4, 2, 3, 1]
  40.  
  41.  
  42. // i=0, what's the idx of the mimimum element from 0 to 4? 4 swap(arr[0], arr[4])
  43.  
  44. // [1, 4, 2, 3, 6]
  45.  
  46. // i=1, what's the idx of the minimum element from 1 to 4? 2 swap(arr[1], arr[2])
  47.  
  48. // [1, 2, 4, 3, 6]
  49.  
  50. // i=2, what's the idx of the mimimum element from 2 to 4? 3 swap(arr[2], arr[3])
  51.  
  52. // [1, 2, 3, 4, 6]
  53.  
  54. // i=3, what'as the idx of the minimum element from 3 to 4? 3 swap(arr[3], arr[3])
  55.  
  56.  
  57. function selectionSort(arr, n) {
  58. for(let i=0;i<n-1;i++) {
  59. // find the idx of the mimimum element from i to n-1
  60. let min_idx = i;
  61.  
  62. for(let j=i;j<n;j++){
  63. if(arr[j] < arr[min_idx]) {
  64. min_idx = j;
  65. }
  66. }
  67. // swap arr[min_idx] with arr[i]
  68. let tmp = arr[min_idx];
  69. arr[min_idx] = arr[i];
  70. arr[i] = tmp;
  71. }
  72. return arr;
  73. }
  74.  
  75. console.log(selectionSort([6, 4, 3, 2, 1], 5))
Success #stdin #stdout 0.04s 18996KB
stdin
Standard input is empty
stdout
1,2,3,4,6