search

Home  >  Q&A  >  body text

js writes a bubble sort

function bubbleSort(arr) {

let n = arr.length;


for (let i = 0; i < n-1 ; i ) {

for (let j = 0; j < n-i-1; j ) {

if (arr[j] > arr[j 1]) {

//Exchange arr[j 1] and arr[j]

let temp = arr[j];

arr[j] = arr[j 1];

arr[j 1] = temp;

}

}

}


return arr ;

}


// Test

let arr = [64, 34, 25, 12, 22, 11, 90] ;

console.log("The array before sorting is: ");

console.log(arr.join(" "));


arr = bubbleSort(arr);

console.log("The sorted array is: ");

console.log(arr.join(" ")) ;


抖音用户822461946抖音用户822461946311 days ago1459

reply all(0)I'll reply

No reply
  • Cancelreply