fork download
  1. // your code goes here
  2. // j < n-i-1
  3. // i=0th pass, j<=n-2 < n-1
  4. // i=1th pass, j<=n-3 < n-2
  5. // i=2th pass, j<=n-4 < n-3
  6. // function bubbleSort(arr, n) {
  7. // for(let i=0;i<n-1;i++){
  8. // for(let j=0;j<n-i-1;j++){
  9. // if(arr[j] > arr[j+1]) {
  10. // // let tmp = arr[j];
  11. // // arr[j] = arr[j+1];
  12. // // arr[j+1] = tmp;
  13. // [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
  14. // }
  15. // }
  16. // }
  17. // return arr;
  18. // }
  19.  
  20. // TC: O(n^2)
  21. // SC: O(1)
  22.  
  23. // console.log(bubbleSort([5, 6, 1, 4, 8], 5))
  24.  
  25. // [5, 6, 1, 4, 8]
  26. // n = 5
  27.  
  28. // i=0, j = 0, 1, 2, 3
  29. // i=1, j = 0, 1, 2
  30. // i=2, j = 0, 1
  31. // i = 3, j = 0
  32.  
  33.  
  34. function selectionSort(arr, n) {
  35. for(let i=0;i<n-1;i++){
  36. let min_idx = i;
  37. for(let j=i+1;j<n;j++){
  38. if(arr[j] < arr[min_idx]) {
  39. min_idx = j;
  40. }
  41. }
  42.  
  43. // min_idx is the index of the least element from i to n-1
  44. [arr[min_idx], arr[i]] = [arr[i], arr[min_idx]];
  45. }
  46. return arr;
  47. }
  48.  
  49. console.log(selectionSort([5, 6, 1, 8, 4], 5))
Success #stdin #stdout 0.04s 16848KB
stdin
Standard input is empty
stdout
1,4,5,6,8