About JS Quick Sort

When participating in an interview, a company asked the question of quick sort, but it was blinded, and only knew about bubble sort, and I didn’t know about quick sort.

First write an example of bubble sort:

var arr = [11,56,66,32,51,39,12];
var times=0
for(var i=0;i<arr.length;i++){
for(var j=i+1;j<arr.length;j++){
if(arr[i]<arr[j]){
var temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

console.log("The "+(++times)+" time after sorting: "+arr);
}
}
console.log(arr);
 
The above code is executed 21 times.
 
function ss (arr){
if(arr.length<=1){
return arr ;
}

var arrIndex=Math.floor(arr.length/2);
var arrIndexNum = arr.splice (arrIndex, 1);
var arrLeft = [];
var arrRight = [];
for(var i=0;i<arr.length;i++){
if(arr[i]<arrIndexNum){
arrLeft.push(arr[i]);
}else{
arrRight.push(arr[i])
}
console.log("The "+(++times)+" time after sorting: "+arr);
}

return ss(arrLeft).concat(arrIndexNum,ss(arrRight))
}

console.log(ss(arr));
Executed 11 times, the efficiency is indeed much faster
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324522867&siteId=291194637