Front-end Algorithms - Comparison of Basic Sorting Algorithms

Basic Sorting Algorithm

  The basic sorting algorithms introduced here mainly include: bubble sort, selection sort, insertion sort, and advanced sorting algorithms such as Hill sort and quick sort will be introduced in subsequent articles. The performance of these algorithms will be compared later in the article.
Basic sorting The core idea of ​​​​the algorithm is to rearrange a set of data in a certain order. The rearrangement is mainly a nested for loop. The outer loop will traverse each item of the array, and the inner loop will compare the elements.
Note: The text is sorted in ascending order For example:

1. Bubble sort

  Bubble sort is one of the slowest sorting algorithms and the easiest to implement. When sorting using this algorithm, data values ​​float like bubbles from one end of the array to the other, so it is called bubble sort . Suppose you want to sort the array in ascending order, larger values ​​will float to the right of the array, and smaller values ​​will float to the left.

principle:

  Start from the first pair of adjacent elements, compare each pair of adjacent elements, if the first is larger than the second, swap the two, so that until the end of the last pair of elements, the last element is the largest number, repeat this process to complete the sorting.

Schematic:

Code:

      function bubbleSort(arr) {
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
              let temp = arr[j];
              arr[j] = arr[j + 1];
              arr[j + 1] = temp;
            }
          }
        }
        return arr;
      }

2. Selection sort

principle:

  First find the smallest element in the current element and put it at the beginning of the sorted sequence, then find the smallest element from the remaining elements, and put it at the end of the sorted sequence. And so on until the sorting is complete.

Schematic:

Code:

      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;
      }

 

3. Insertion sort

principle:

  Starting from the second element (assuming the first element is already sorted), take this element, compare the sorted elements from back to front, and if the element is larger than this element, move the element to the next position , and then continue to compare forward until a position less than or equal to the element is found, and the element is inserted at this position. Repeat this step until the sorting is complete.

Schematic:

Code: 

      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;
      }

4. Performance Comparison of Basic Sorting Algorithms

  Use console.time for time calculation, write console.time at the beginning of the test, and pass a string in parentheses. Use the console.timeEnd method at the end, and pass in the string again to view the execution time on the console.
First create an n-bit random array for testing.

      function createRandomArr(n) {
        let arr = [];
        for (let i = 0; i < n; i++) {
          arr.push(Math.floor((Math.random() * 100)));
        }
        return arr;
      }

Record the time used by the three algorithms respectively:

  var testArr = createRandomArr(1000 );
   //   Record the time spent in bubble sort 
  console.time('bubbleSort' );
  bubbleSort(testArr);
  console.timeEnd( 'bubbleSort' );
   var testArr = createRandomArr(1000 );
   //   Record the time used for selection sorting 
  console.time('selectionSort' );
  selectionSort(testArr);
  console.timeEnd( 'selectionSort' );
   var testArr = createRandomArr(1000 );
   //   Record the time used for insertion sorting 
  console.time('insertionSort' );
  insertionSort(testArr);
  console.timeEnd('insertionSort');

Execute the code in Chrome and see their execution time comparison in the console, Duang Duang Duang!

Of course, multiple runs are required before the results can be considered valid conclusions. Obviously, insertion sort is faster than the other two sorting methods.

 

Note: The pictures in the text are transferred from: https://www.cnblogs.com/onepixel/articles/7674659.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324620345&siteId=291194637