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