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