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