Three generic classes of sorting method

//Bubble Sort
function maopao (arr) {
for(var i=0;i<arr.length-1;i++){
for(var j=0;j<arr.length-1-i;j++){
if(arr[j]<arr[i+1]){
var temp=arr[j];
arr [j] = arr [j + 1];
arr[j+1]=temp;
}
}
}
return arr
}
// selection sort
function xuanze (arr) {
for(var i=0;i<arr.length-1;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;
}
}
}
return arr
}
// quick sort row
/**
* 1 first determines the length of the array, the array if the length is less than or equal to 1, returns directly to the array
* 2. Select a reference to compare with other elements, where the first element is selected as the reference array
* 3. Define two empty array, the elements used to store large newArrAfter than the reference element and smaller than the reference element newArrBefore
* 4 The newArrAfter and newArrBefore also arr [0] and returns splicing
* 5. Recursive, each to a determined array elements in the array until only a
*/
function fast(arr){
if (arr.length<=1) return arr;
was newArrBefore = [];
was newArrAfter = [];
for(var i=1;i<arr.length;i++){
arr[0]>arr[i]?newArrBefore.unshift(arr[i]):newArrAfter.push(arr[i])
}
return fast(newArrBefore).concat(arr[0],fast(newArrAfter))
}
arr=[19,20,38,4,57,18];
console.log (maopao (arr))
console.log (xuanze (arr))
console.log(fast(arr))

Guess you like

Origin www.cnblogs.com/guozhuang/p/10963154.html