Home  >  Article  >  Web Front-end  >  js sorting algorithm

js sorting algorithm

不言
不言Original
2018-04-10 11:56:471020browse

The content introduced in this article is about the sorting algorithm of js. Now I will share it with you. Friends in need can refer to it.

The content introduced in this article is about the sorting algorithm of js. Now I will share it with you. Everyone, friends in need can refer to

/*冒泡排序*/function bubbleSort(arr){
    var len = arr.length;    for(var i = 0;i<len-1;i++){        for(var j = i+1;j<len-i-1;j++){            if(arr[j]>arr[j+1]){                var temp = arr[j+1];
                arr[j+1] = arr[j];
                arr[j] = temp
            }
        }
    }    return arr
}
/*快速排序排序*/var quickSort = function(arr){
    if(arr.length<=0){        return arr;
    }    var midIndex = Math.foor(arr.length/2);    var midValue = arr.splice(midIndex,1);    var left =[];    var right = [];    for(var i =0;i<arr.length;i++){        if(arr[i]<midValue){
            left.push(arr[i]);
        }else{
            right.push(arr[i]);
        }
    }    return quickSort(left).concat(midValue,quickSort(right));
}
/*选择排序*/function selectionSort(arr){
    var len = arr.length;    var midIndex,temp;    for(var i =0 ;i<len-1;i++){
        midIndex = i;        for(var j=i+1;j<len;j++){            if(arr[j]<arr[midIndex]){
                midIndex = j;
            }
        }
        temp = arr[i];
        arr[i]= arr[midIndex];
        arr[midIndex] = temp;
    }    return arr
}

Related recommendations:

Two practical js sorting algorithm analysis

commonly used JS sorting algorithm

         

The above is the detailed content of js sorting algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Make a clock with JSNext article:Make a clock with JS