fork download
  1. // your code goes here
  2. function bubbleSort(arr, n) {
  3. for(let i=0;i<n-1;i++) {
  4. for(let j=0;j<n-i-1;j++) { // iteration 0: j = 0 to n-2
  5. if(arr[j]>arr[j+1]) {
  6. let tmp = arr[j];
  7. arr[j] = arr[j+1];
  8. arr[j+1] = tmp;
  9.  
  10. // [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
  11. }
  12. }
  13. }
  14. return arr;
  15. }
  16.  
  17. function selectionSort(arr, n) {
  18.  
  19. for(let i=0;i<n-1;i++){
  20. // find the index of the minimum element from i to n-1
  21. let min_elem_idx = i;
  22. for(let j=i+1;j<n;j++) {
  23. if(arr[j] < arr[min_elem_idx]) {
  24. min_elem_idx = j;
  25. }
  26. }
  27.  
  28. // swap min_elem_idx element with arr[i]
  29. let tmp = arr[i];
  30. arr[i] = arr[min_elem_idx];
  31. arr[min_elem_idx] = tmp;
  32. }
  33. return arr;
  34. }
  35.  
  36. console.log(selectionSort([6, 3, 1, 7, 4], 5))
Success #stdin #stdout 0.03s 16672KB
stdin
Standard input is empty
stdout
1,3,4,6,7