JS 排序

xiaoxiao2021-02-28  17

一、需求:对数组进行排序

1、sort

function compare( a , b ){ return a-b }

arr.sort(compare);

2、冒泡排序

    ...    

3、快速排序(能衍生一个二分查找)//***这个是一个伪快排

function twoSort( arr ){

    if(arr.length <= 1){ return arr }

    var mid = arr.splice(Math.floor( arr.length/2 ) ,1 );

    var left = [] , right = [];

    for(var i = 1; i < arr.length; i++){

        if(arr[i]<mid){

            left.push( arr[i] );

        }else{

            right.push( arr[i] );

        }

    }

    return twoSort(left).concat(mid , twoSort(right))

比较推崇 https://www.cnblogs.com/dushao/p/6004883.html

function quickSort(arr, left, right) { var len = arr.length, partitionIndex, left = typeof left != 'number' ? 0 : left, right = typeof right != 'number' ? len - 1 : right; if (left < right) { partitionIndex = partition(arr, left, right); quickSort(arr, left, partitionIndex-1); quickSort(arr, partitionIndex+1, right); } return arr; } function partition(arr, left ,right) { //分区操作 var pivot = left, //设定基准值(pivot index = pivot + 1; for (var i = index; i <= right; i++) { if (arr[i] < arr[pivot]) { swap(arr, i, index); index++; } } swap(arr, pivot, index - 1); return index-1; } function swap(arr, i, j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }

转载请注明原文地址: https://www.6miu.com/read-2600104.html

最新回复(0)