fork download
  1. // your code goes here
  2. function bubbleSort(arr, n) {
  3.  
  4. for(let i=0;i<n-1;i++) {
  5. for(let j=0;j<=n-2-i;j++) {
  6. // jth and (j+1)th elements
  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. }
  13. }
  14. return arr;
  15. }
  16.  
  17. // console.log(bubbleSort([4, 1, 7, 2, 3], 5))
  18.  
  19. // TC: O(n^2)
  20. // SC: O(1)
  21.  
  22. function selectionSort(arr, n) {
  23. for(let i=0;i<n-1;i++) {
  24. let min_elem_idx = i;
  25. for(let j=i+1;j<n;j++){
  26. if(arr[j] < arr[min_elem_idx]) {
  27. min_elem_idx = j;
  28. }
  29. }
  30. // swap arr[i] with arr[min_elem_idx]
  31. let tmp = arr[i];
  32. arr[i] = arr[min_elem_idx];
  33. arr[min_elem_idx] = tmp;
  34. }
  35. return arr;
  36. }
  37.  
  38. console.log(selectionSort([4, 1, 7, 2, 3], 5))
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
Success #stdin #stdout 0.03s 16840KB
stdin
Standard input is empty
stdout
1,2,3,4,7