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