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