手写数组排序

        //冒泡排序
        function bubble(arr){
            var i,j
            var len = arr.length
            for(i=0; i<len; i++){
                for(j=0; j<len-i-1; j++){
                    if(arr[j]>arr[j+1]){
                        let temp = arr[j]
                        arr[j] = arr[j+1]
                        arr[j+1] = temp
                    }
                }
            }
            return arr
        }
        //选择排序
        function choose(arr){
            var i,j
            var len = arr.length
            for(i=0; i<len; i++){
                for(j=i+1; j<len; j++){
                    if(arr[i]>arr[j]){
                        let temp = arr[i]
                        arr[i] = arr[j]
                        arr[j] = temp
                    }
                }
            }
            return arr
        }
        //插入排序
        function insertion(arr){
            var i,current,prevIdx
            var len = arr.length
            for(i=1; i<len; i++){
                current = arr[i]
                prevIdx = i-1
                while(prevIdx>=0 && current<arr[prevIdx]){
                    arr[prevIdx+1] = arr[prevIdx]
                    prevIdx--
                }
                arr[prevIdx+1] = current
            }
            return arr
        }
        //快速排序
        function quick(arr){
            var len = arr.length
            var key = arr[Math.floor(len/2)]
            var left = [], right = [], mid = [], current
            if(len < 2){
                return arr
            }
            for(var i=0; i<len; i++){
                current = arr[i]
                if(current < key){
                    left.push(current)
                }else if(current > key){
                    right.push(current)
                }else{
                    mid.push(current)
                }
            }
            return [].concat(quick(left),mid,quick(right))
        }

 

posted @ 2020-12-21 20:58  `Duet`  阅读(196)  评论(0编辑  收藏  举报