The only js array sorting method in the whole network (invented sorting)

Sorting principle : First find the maximum value in the array, starting from 0 and adding 1 each time (0, 1, 2, 3,..., max). Then judge whether the number in the array is equal to it, and if it is equal, throw it to the new array to complete the sorting

This sort uses a method of taking the maximum value of the array. as follows

var max = Math.max.apply(null,arr)
 function zichuang(arr){
    
     //参数是任意一个数组
        var max = Math.max.apply(null,arr); // 取数组最大值 别疑惑 这一步很简单(Math.max.apply()取数组最大值的方法)  
        // console.log(max)
        var newArr = []; // 创建一个新数组
        for(var i = 0; i <= max;i++){
    
     // 第一层循环是从0开始到最大值max结束
            for(var j = 0;j < arr.length;j++){
    
     // 第二层是遍历老数组
                if(arr[j] == i){
    
    
                    newArr.push(arr[j]) // 如果数组中有一个数等于第一层循环中的数 就往新数组中添加
                }
            }
        }
        return newArr
    }
    console.log(zichuang([4,2,1,6,3,8])) // 最后输出[1,2,3,4,6,8]

Disadvantages of this sorting : too many cycles, the same as counting the number of cycles of sorting. That is, if the array is [1,1000], it will still loop 1000 times, because it will loop at least the number of times worth the maximum value of the array.

Advantages of this sorting : sorting, de-duplication, and counting can be done at the same time.

Guess you like

Origin blog.csdn.net/ironlccc/article/details/114100921