[Algorithms and Data Structures] JavaScript implements the top ten sorting algorithms (1)

About sorting algorithms

Insert image description here

Stable sorting: Elements with the same key value during the sorting process still maintain their relative original order after sorting. This means that there are now two elements a and b, a is ranked in front of b, and a==b. After sorting, a is still in front of b. This is a stable sorting.

Unstable sorting: Elements with the same key value during the sorting process may change their relative order after sorting. This means that there are now two elements a and b. In the original sequence, a is in front of b. After sorting, a may appear after b, and their relative positions may change.

In-situ sorting: There is no need to apply for extra storage space during the sorting process, and only the storage space that originally stored the data to be sorted is used for comparison and exchange of data sorting. This means that in in-place sorting, the sorting operation directly modifies the original data without creating a new data structure to store the sorted results.

Non-in-place sorting: During the sorting process, you need to apply for additional storage space to store temporary data or sorting results without directly modifying the original data.

Bubble Sort

The basic idea: through comparison and exchange between adjacent elements, elements with small sorting codes are gradually moved from the bottom to the top. Because the entire sorting process gradually rises up like bubbles under water, it is called bubble sorting.

Steps:

  • Compares two adjacent elements. If the first element is larger than the second element, swap the two elements;
  • Repeat the above steps until the end of the array;
  • Repeat the above two steps until sorting is complete.
    Insert image description here

example:

Sort from a=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]small to large.

  <script>
    function BubbleSort(arr) {
    
    
      for (let i in arr) {
    
    
        // 每次循环都能找到一个最大的数放在最右边
        for (let j = 0; j < arr.length - 1 - i; j++) {
    
    
          if (arr[j] > arr[j + 1]) {
    
    
            let temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
          }
        }
      }
      console.log(arr);
      return arr
    }
    let a = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
    BubbleSort(a)
  </script>

Summary: Stable sorting requires very little space. The space complexity is O(1) and the time complexity is O(n²).

selection sort

Basic idea: First find the smallest (large) element in the unsorted sequence and store it at the starting position of the sort. Then continue to find the smallest (large) element from the remaining unsorted elements and place it at the starting position of the sorted sequence. And so on until all elements have been sorted.

Steps:

  • Find the smallest (largest) element within the array range and exchange it with the starting position element;
  • In addition to the elements that have been sorted, find the smallest (largest) element in the remaining array range and exchange it with the starting element of the remaining array.
    Insert image description here
    example:

Sort from a=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]small to large.

  <script>
    function SelectionSort(arr) {
    
    
      for (let i in arr) {
    
    
        // 声明一个变量,用来接收当前最小值的下标
        let min = i
        for (let j = i; j < arr.length; j++) {
    
    
          if (arr[j] < arr[min]) {
    
    
            min = j
          }
        }
        let temp = arr[i]
        arr[i] = arr[min]
        arr[min] = temp
      }
      console.log(arr);
      return arr
    }
    let a = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
    SelectionSort(a)
  </script>

Analysis: Unstable sorting requires very little space. The space complexity is O(1) and the time complexity is O(n²).

insertion sort

Basic idea: Divide the array into two parts, one part is sorted and the other part is unsorted. Initially, the sorted part only contains the first element of the array, and then the elements of the unsorted part are inserted into the sorted part in order, so that the sorted part still remains in order.

Steps:

  • Use the first number as the benchmark, take out the second number and compare it. If it is larger than it, put it on the right; if it is smaller, put it on the left;
  • Take out the third number and compare it with the previous number. If it is larger, put it on the right side. If it is smaller, compare it with the previous number until you encounter a smaller number;
  • Keep repeating the above steps
    Insert image description here
    . Example:

Sort from a=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]small to large.

  <script>
    function InsertionSort(arr) {
    
    
      // 以第一个数作为基准
      for (let i = 1; i < arr.length; i++) {
    
    
        let temp = arr[i]
        let j;
        // 如果遍历的元素大于取出的元素,则遍历过的元素都需要后移一位
        for (j = i - 1; j >= 0 && a[j] > temp; j--) {
    
    
          arr[j + 1] = arr[j]
        }
        arr[j + 1] = temp
      }
      console.log(arr);
    }
    let a = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
    InsertionSort(a)
  </script>

Analysis: Stable sorting requires very little space. The space complexity is O(1) and the time complexity is O(n²).

Hill sort

Basic idea: It is an improved version of insertion sort. It divides the original array into multiple subsequences, uses insertion sort to sort the subsequences, and finally merges them into an ordered sequence.

Steps:

  • Choose an increment sequence (interval sequence), usually with an initial increment of half the array length and then gradually decreasing increments;
  • Divide the original array into multiple subsequences in increments. Each subsequence can be viewed as a small array;
  • Apply the insertion sort algorithm to each subsequence to sort the elements in the subsequence;
  • Gradually reduce the increment and repeat the above steps until the increment is 1;
  • When the last increment is 1, the entire array is treated as a sequence and insertion sort is applied again.

Insert image description here

example:

Sort from a=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]small to large.

  <script>
    function ShellSort(arr) {
    
    
      // 选择初始的增量(gap)为数组长度的一半Math.floor(arr.length / 2)
      for (let gap = Math.floor(arr.length / 2); gap > 0; gap = Math.floor(gap / 2)) {
    
    
        // 对每个子序列进行插入排序
        for (let i = gap; i < arr.length; i++) {
    
    
          const temp = arr[i]
          let j;
          for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {
    
    
            arr[j + gap] = arr[j]
          }
          arr[j + gap] = temp
        }
      }
      console.log(arr);
    }
    let a = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
    ShellSort(a)
  </script>

Analysis: Unstable sorting requires very little space. The space complexity is O(1) and the time complexity is O(nlog(n)).

merge sort

Basic idea: It is a sorting algorithm based on the divide-and-conquer strategy. It divides the array to be sorted into several subsequences, sorts them separately, and then merges these subsequences to achieve overall ordering. The main steps of merge sort include three stages: splitting, sorting and merging.

Steps:

  • Split: Divide the array to be sorted into two roughly equal sub-arrays, and sort the two sub-arrays recursively;
  • Sorting: Sort each subarray recursively until the length of the subarray is 1 (only one element), at which point it is considered ordered;
  • Merge: Merge the sorted subarrays into a new ordered array. The key to this step is to merge the two ordered subarrays into a larger ordered array.
    Insert image description here
    example:

Sort from a=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]small to large.

  <script>
    function MergeSort(arr) {
    
    
      if (arr.length <= 1) return arr;

      // 分割数组
      const middle = Math.floor(arr.length / 2)
      const left = arr.slice(0, middle)
      const right = arr.slice(middle)
      // 递归分割+排序
      const leftSort = MergeSort(left)
      const rightSort = MergeSort(right)

      return SequencSort(leftSort, rightSort)
    }
    function SequencSort(left, right) {
    
    
      let result = []
      let leftIndex = 0;
      let rightIndex = 0;
      // 合并两个有序数组
      while (leftIndex < left.length && rightIndex < right.length) {
    
    
        if (left[leftIndex] < right[rightIndex]) {
    
    
          result.push(left[leftIndex])
          leftIndex++
        } else {
    
    
          result.push(right[rightIndex])
          rightIndex++
        }
      }
      // 将剩余的元素添加到结果中
      return result.concat(left.slice(leftIndex), right.slice(rightIndex))
    }
    let a = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
    MergeSort(a)
  </script>

Analysis: Stable sorting, space complexity is O(n), time complexity is O(nlog(n)).

Guess you like

Origin blog.csdn.net/aDiaoYa_/article/details/133122263