The front end of the interview often test of 10 large sorting algorithm

Preface

  The front post requirements compared to other IT jobs, the algorithm is still relatively low. But I have experienced the white school recruit interview Tencent, Alibaba, Baidu and other manufacturers, found that the basic idea or algorithm must master. So in recent years, slowly I began to study the basic algorithms and found that "JavaScript data structures and algorithms described in" front-end is particularly suitable for reading.

   Next, we analyze the 10 ideas and algorithms usage scenarios often test the next interview.

First, the bubble sort (Bubble Sort)

  Bubble sort is the easiest method of ordering ordering exchange, the main idea is: a sequence selected two adjacent numbers in the record to be sorted, if the exchange reverse order, until there is no reverse order of the series so far.

1, the algorithm description

  • Compare adjacent elements. If the first is larger than a second, to exchange their two;
  • We do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair, so that should be the last element is the largest number;
  • Repeating the above steps for all elements, except the last one;
  • Repeat steps 1 to 3 until the sorting is completed.

2, code implementation

function bubbleSort(arr) {
    var len = arr.length;
    for(var i = 0;i < len;i++) {
        for(var j = 0;j < len-1-i;j++) {
            if(arr[j] > arr[j+1]) {// 相邻元素两两比较
                var temp = arr[j+1];// 元素交换
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
复制代码

Second, the quick sort (Quick Sort)

  Quick sort , bubble sort is a kind of improvement. In the quick sort, record and compare the movement is carried out from both ends to the middle, a large value can be recorded once moved from the front to the back, a small value can be recorded once moved from the back to the front, thus reducing the overall the number of comparisons, and mobile number.

1, the algorithm description

Quicksort using a divide and conquer the column number (list) into the number of columns 2 (sub-lists), the specific algorithm is as follows:

  • Pick one element from the series, referred to as a "reference" (Pivot);
  • Reorder columns, all the elements are placed in front of the small base than the reference value, all the elements placed behind the baseline larger than the reference value (the same number can be either side). After the partition exit, on the basis of the number of columns in the middle position. This is called a partition (Partition) operation;
  • Number of sub recursively (recursive This) than the reference value the number of columns and the sub-element is greater than the reference value of the element column.

2, code implementation

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);
    }
}
// 分区操作
function partition(arr, left, right) { 
    // 设定基准值pivot
    var pivot = left,
        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;
}
复制代码

Third, insertion sort (Insertion Sort)

  Insertion sort , is a class of methods by "Insert" sort, the main idea is: every time a number to be sorted according to their size key has been inserted into a properly arranged in an ordered sequence, until all rows of numbers good order.

1, the algorithm description

Insert sequencing using in-place in the array to achieve the specific algorithm described as follows:

  • Starting with the first element, which can be considered to have been sorted;
  • Remove the next element from the forward scan has been sorted in the sequence of elements;
  • If the element (sorted) is greater than the new element, the element to the next position;
  • Repeat step 3 until it finds the sorted elements less than or equal to the new position of the element;
  • After the new element is inserted into this position;
  • Repeat steps 2-5.

2, code implementation

function insertionSort(arr) {
    var len = arr.length;
    var preIndex, current;// 从后向前扫描索引,当前元素数值
    for(var i = 1;i<len;i++) {
        preIndex = i-1;
        current = arr[i];
        while(preIndex >= 0 && arr[preIndex] > current) {
            arr[preIndex+1] = arr[preIndex];
            preIndex--;
        }
        arr[preIndex+1] = current;
    }
    return arr;
}
复制代码

Fourth, Hill sorting (Shell Sort)

  Shell sort , insertion sort is an improvement, which is the basic idea of the sort: first the entire sequence to be sorted into a number of subsequences, are performed in sequence direct insertion sort, to be ordered substantially the entire sequence, and then the The overall sequence once insertion sort.

1, the algorithm description

  • Selecting an incremental sequence t1, t2, ..., tk, where ti> tj, tk = 1;
  • Increments the sequence number k, k times the sequence is sorted;
  • Sort per trip, according to the corresponding increment ti, a column to be sorted into several sub-sequences of length m of each sub-table for each direct insertion sort. Only the delta factor is 1, the entire sequence as a processing table, the table length is the length of the entire sequence.

2, code implementation

function SellSort(arr) {
    var len = arr.length;
    for(var gap = Math.floor(len / 2); gap > 0; gap = Math.floor(gap / 2)) {
        // 多个分组交替执行
        for(var i = gap; i < len;i++) {
            var j = i;
            var current = arr[i];
            while (j - gap >= 0 && current < arr[j - gap]) {
                 arr[j] = arr[j - gap];
                 j = j - gap;
            }
            arr[j] = current;
        }
    }
    return arr;
}
复制代码

Fifth, the selection sort (Selection Sort)

  Selection sort , is a simple and intuitive sorting algorithm, the basic idea is: First, the minimum value is selected to be sorted sequence, stored in the collating sequence start position, and then continue to look for the minimum element from the remaining unsorted elements, put to the end of the sorted sequence. And so on, until all the elements are sorted.

1, the algorithm description

Direct selection sort n records may be n-1 times via direct selection orderly sorting result. The algorithm is described as follows:

  • Initial state: disordered region is R [1..n], ordered regions is empty;
  • Run ordering the i (i = 1,2,3 ... n-1) starts, the current ordered regions and disordered regions were R [1..i-1] and R (i..n). The trip from the current sorting disordered zone - Minimum recording key selected R [K], it will exchange with the first record disordered region R, so that R [1..i] and R [i + 1 ..n) were changed to increase the number of records and the number of records a new order to reduce a new area of ​​disorder;
  • n-1 the end of the trip, the ordered array.

2, code implementation

function selectionSort(arr) {
    var len = arr.length;
    var minIndex, temp;
    for(var i = 0; i< len-1;i++){
        minIndex = i;
        for(var j = i+1;j<len;j++) {
            if(arr[j] < arr[minIndex]) {// 寻找最小的数
                minIndex = j;
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
    return arr;
}
复制代码

Sixth, heap sort (Heap Sort)

  Heap sort , heap sort algorithm is used a data structure design. Heap is a complete binary tree with the following properties: the value of each node is less than or equal to the value of the left and right child nodes (root called small stack); or the value of each node is equal to or greater than the left and right child nodes value (referred to as large heap root).

1, the algorithm description

  • The initial key string to be sorted (R1, R2 ... .Rn) constructed to be larger than the top of the stack, the stack of the initial disordered region;
  • The top of the stack of elements R [. 1] and the last element of R [n-] exchanged, this time to obtain the new disordered regions (R1, R2, ...... Rn-1) and the new ordered regions (Rn of), and satisfying R [1,2 ... n-1] <= R [n];
  • Since the new top of the stack after an exchange of R [1] may be in violation of the nature of the stack, it is necessary for the current disordered regions (R1, R2, ...... Rn-1) is adjusted to the new stack, and then again R [1] and disordered exchange the last element area results in a new disordered regions (R1, R2 ... .Rn-2) and the new ordered regions (Rn-1, Rn). This process is repeated until the number of elements ordered regions of n-1, the entire sorting process is complete.

2, code implementation

// 多个函数需要用到数据长度,把len设为全局变量
var len; 
// 建立大顶堆
function buildMaxHeap(arr) {
    len = arr.length;
    for(var i = Math.floor(len/2); i >= 0;i--) {
        heapify(arr, i);
    }
}
// 堆调整
function heapify(arr, i) {
     var left = 2 * i + 1,
        right = 2 * i + 2,
        largest = i;

    if (left < len && arr[left] > arr[largest]) {
        largest = left;
    }

    if (right < len && arr[right] > arr[largest]) {
        largest = right;
    }

    if (largest != i) {
        swap(arr, i, largest);
        heapify(arr, largest);
    }
}
function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function HeapSort(arr) {
    buildMaxHeap(arr);
}
复制代码

Seven, merge sort (Merge Sort)

  Merge sort , it is a method by means of "merge" sort, merge the meaning of the two or more ordered sequences merge into an ordered sequence of processes. The main idea of merge sort: the number of ordered sequence gradually merge, eventually merged into an ordered sequence.

1, the algorithm description

  • The length n of the input sequence is divided into two sub-sequences of length n / 2; and
  • These two sequences were used to merge sort;
  • The two combined sequences sorted into a final sorted sequence.

2, code implementation

function mergeSort(arr) {  //采用自上而下的递归方法
    var len = arr.length;
    if(len < 2) {
        return arr;
    }
    var middle = Math.floor(len / 2),
        left = arr.slice(0, middle),
        right = arr.slice(middle);
    return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right) {
    var result = [];
 
    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }
 
    while (left.length)
        result.push(left.shift());
 
    while (right.length)
        result.push(right.shift());
 
    return result;
}
复制代码

Eight, count sort (Counting Sort)

  Counting sorting , sorting algorithms are not based on the comparison, the core is the data value into the input keys stored in an array of additional space open. A linear sort time complexity, the data input count ordering requirements must be integers determined range.

1, the algorithm description

  • The array to be sorted to find the largest and smallest element;
  • Count the number of each element in the array is i occurring, stored in the array C of the i-th item;
  • All of the accumulated count (starting from the first element C, and one each before adding);
  • Reverse fill the target array: i on each element of the new array C (i) of each element will be put C (i) minus one.

2, code implementation

function countingSort(arr, maxValue) {
    var bucket = new Array(maxValue + 1),
        sortedIndex = 0;
        arrLen = arr.length,
        bucketLen = maxValue + 1;
 
    for (var i = 0; i < arrLen; i++) {
        if (!bucket[arr[i]]) {
            bucket[arr[i]] = 0;
        }
        bucket[arr[i]]++;
    }
 
    for (var j = 0; j < bucketLen; j++) {
        while(bucket[j] > 0) {
            arr[sortedIndex++] = j;
            bucket[j]--;
        }
    }
 
    return arr;
}
复制代码

Nine, bucket sort (Bucket Sort)

  Bucket sort , is a simple ordered distribution, its working principle: Assuming that the input data is uniformly distributed, the data assigned to a limited number of buckets, each bucket were then sorted (it is possible to reuse or to another sorting algorithm recursively continue to use the bucket sort performed row).

1, the algorithm description

  • Array as a set of quantitative hollow barrel;
  • Traversing input data, and a data corresponding to a bucket to put;
  • And sorting each bucket is not empty;
  • Not empty bucket from the sorted data spliced ​​together.

2, code implementation

function bucketSort(arr, bucketSize) {
    if (arr.length === 0) {
      return arr;
    }
 
    var i;
    var minValue = arr[0];
    var maxValue = arr[0];
    for (i = 1; i < arr.length; i++) {
      if (arr[i] < minValue) {
          minValue = arr[i];                // 输入数据的最小值
      } else if (arr[i] > maxValue) {
          maxValue = arr[i];                // 输入数据的最大值
      }
    }
 
    // 桶的初始化
    var DEFAULT_BUCKET_SIZE = 5;            // 设置桶的默认数量为5
    bucketSize = bucketSize || DEFAULT_BUCKET_SIZE;
    var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;  
    var buckets = new Array(bucketCount);
    for (i = 0; i < buckets.length; i++) {
        buckets[i] = [];
    }
 
    // 利用映射函数将数据分配到各个桶中
    for (i = 0; i < arr.length; i++) {
        buckets[Math.floor((arr[i] - minValue) / bucketSize)].push(arr[i]);
    }
 
    arr.length = 0;
    for (i = 0; i < buckets.length; i++) {
        insertionSort(buckets[i]);                      // 对每个桶进行排序,这里使用了插入排序
        for (var j = 0; j < buckets[i].length; j++) {
            arr.push(buckets[i][j]);                     
        }
    }
 
    return arr;
}
复制代码

Ten, radix sort (Radix Sort)

  Radix sort , is in accordance with the low first sorted and then collected; then sorted according to high, and then collect; and so on, up to the highest position.

1, the algorithm description

  • Get the maximum number of array and obtain the number of bits;
  • arr original array, began to take each array of radix bits from the least significant bit;
  • Radix sort of counting (counting sequencing using a suitable number of small-scale features).

2, code implementation

var counter = [];
function radixSort(arr, maxDigit) {
    var mod = 10;
    var dev = 1;
    for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
        for(var j = 0; j < arr.length; j++) {
            var bucket = parseInt((arr[j] % mod) / dev);
            if(counter[bucket]==null) {
                counter[bucket] = [];
            }
            counter[bucket].push(arr[j]);
        }
        var pos = 0;
        for(var j = 0; j < counter.length; j++) {
            var value = null;
            if(counter[j]!=null) {
                while ((value = counter[j].shift()) != null) {
                      arr[pos++] = value;
                }
          }
        }
    }
    return arr;
}
复制代码

to sum up

  10 kinds of sorting algorithms do the following summary comparison, as shown:

  The average time complexity point of view, seven kinds of comparison sorted from low to high efficiency are:
  bubble sort insertion sort ≈ ≈ Selection Sort <Shell sort <heap sort <merge sort <quicksort

  Quicksort is most efficient for large data value and the random arrangement. However, if the data has been substantially ordered, the efficiency deteriorates to O (n ^ 2).

  Bubble sort is the slowest sorting algorithm, in practice the lowest efficiency of the algorithm, time complexity is O (n ^ 2).

  Select the sort In practice, bubble sort and almost all the same, less use.

  Insertion sort 2 times faster than bubble sort. Generally not suitable where large amount of data or data repetition more occasions.

  Hill sorting five times faster than bubble sort, approximately two times faster than the insertion sort. Shell sort than the quick sort, merge sort, heap sort is much slower. But shell algorithm is relatively simple, especially for the amount of data and the performance is not very high in the case of 5,000 or less.

  Heap sort is not required or a large number of temporary recursive multi-dimensional array, only one scratch space for exchange, so that for a very large amount of sequence data is appropriate.

  Merge sort than the heap sort slightly faster, because it requires an extra array, and therefore need more memory than the heap sort.

  Sorting algorithm profound data structure, now I just summed up the 10 kinds of common algorithm, later learning other sorting algorithms, and then continue to discuss with you ~

Reproduced in: https: //juejin.im/post/5cff4b6ae51d4558936aa05a

Guess you like

Origin blog.csdn.net/weixin_33672400/article/details/93178348