JavaScript common sorting algorithm ideas and code implementation

Bubble Sort

By comparison and exchange of adjacent elements, each pass so that the cycle can not find the maximum or minimum of the sorted array.
Best: O(n)only need one bubble array on the order.
Worst: O (n²)
Average: O (n²)

* Single bubble

  function bubbleSort(nums) {
        for (let i=0 , len=nums.length; i<len-1; i++) {
          //如果一轮比较中没有需要交换的数据,则说明数组已经有序,主要是为了对[5,1,2,3,4]之类的数组进行优化。
            let mark = true;
            for (let j = 0; j < len-i-1; i++) {
                if (nums[j] > nums[j+1]) {
                    [nums[j],nums[j+1]] = [nums[j+1],nums[j]]
                    mark = false
                }
            }
            if (mark) return nums
        }
    }

Bidirectional bubble

Ordinary bubble sort loop in the trip only to find a maximum or minimum, bi-directional bubble is more than one cycle only to find out the maximum value can also find the minimum value

     function bubbleSort_twoWays(nums) {
            let low = 0
            let high = nums.length - 1
            while(low < high) {
                let mark = true
                // 找到最大值放到到右边
                for (let i=low; i<high; i++) {
                    if(nums[i] > nums[i+1]) {
                        [nums[i],nums[i+1]] = [nums[i+1],nums[i]]
                        mark = false
                    }
                }
                high--
                // 找到最小值放到左边
                for(let j=high;j>low;j--) {
                    if(nums[j] < nums[j-1]) {
                        [nums[j],nums[j-1]] = [nums[j-1],nums[j]]
                        mark = false
                    }
                }
                low++
                if(mark) return nums
            }
        }

Selection Sort

And bubble sort is similar, except that the sort is selected element and each of its later comparison and exchange elements.

Preferably: O (n²)
Worst: O (n²)
Average: O (n²)

 function selectSort(nums) {
            for (let i = 0, len = nums.length; i < len; i++) {
                for (let j = i + 1; j < len; j++) {
                    if (nums[i] > nums[j]) {
                        [nums[i], nums[j]] = [nums[j], nums[i]]
                    }
                }
            }
            return nums
        }

Insertion sort
to the first element as an ordered array, by subsequent elements find a suitable location in the array has been ordered and insert.

The best: O(n)the original array is already ascending.
Worst: O(n²)
Average:O(n²)

function insertSort(nums) {
            for (let i = 1,len = nums.length;i < len; i++) {
                let temp = nums[i]
                let j = i
                while (j >= 0 && temp < nums[j-1]) {
                    nums[j] = nums[j-1]
                    j--
                }
                nums[j] = temp
            }
            return nums
        }

Quick Sort

Select an element as the base (usually the first element), the base element is smaller than the left into it, larger than the base element into its right (equivalent to 22 minutes), and then continue recursively base sequences on both sides of the left and right.

Preferably: O (n * logn), all numbers uniformly distributed on both sides of the base, this time constant is about recursive binary sequence.
Worst: O (n²), all numbers are located on one side of the base, this time sequence is the equivalent of approximately divide insertion sort.
Average: O (n * logn)

  • Quick sort of fill hole

From the right time after advancing to the middle encountered a number less than the base would be assigned to the left (the beginning is the location of the base), the right to retain the original value, etc. are left to fill in values

Counting Sort

An array element is key, as the number of occurrences of value deposited into a temporary array, and finally traverse the temporary array to revert back to the original array. Because arrays are standard strings stored in JavaScript, so the arrangement can be used to count negative sort, but not aligned decimals.

Preferably: O (n + k), k is the difference between the maximum and minimum values.
Worst: O (n + k)
Average: O (n + k)

 function countingSort(nums) {
            let arr = []
            let max = Math.max(...nums)
            let min = Math.min(...nums)
            // 装桶
            for (let i=0, len=nums.length; i<len; i++) {
                let temp = nums[i]
                arr[temp] = arr[temp] + 1 || 1
            }
            let index = 0
            //还原数组
            for (let i=min; i<=max; i++) {
                while(arr[i]>0) {
                    nums[index++] = i
                    arr[i]--
                }
            }
            return nums
        }

Shell sort

GAP by some increment, the entire sequence is divided into groups, and comparing the members of the group switching from the back, and then gradually reduced to 1 increment. Hill sorting similar to insert sequencing, only a few steps beginning from a forward movement into a gap.

Preferably: O (n * logn), continue to step two.
Worst: O (n * logn)
Average: O (n * logn)


        function shellSort(nums) {
            let len = nums.length
            // 初始步数
            let gap = parseInt(len / 2)
            // 逐渐缩小步数
            while (gap) {
                // 从第gap个元素开始遍历
                for (let i = gap; i < len; i++) {
                    //逐步和前面其他成员进行比较和交换
                    for (let j = i - gap; j >= 0; j -= gap) {
                        if (nums[j] > nums[j + gap]) {
                            [nums[j], nums[j + gap]] = [nums[j + gap], nums[j]]
                        } else {
                            break
                        }
                    }
                }
                gap = parseInt(gap / 2)
            }
            return nums
        }

Original link: https: //mp.weixin.qq.com/s/Rl_fcWzcSQ7NkPnozIrt0A

Guess you like

Origin www.cnblogs.com/yuanchao-blog/p/10990628.html