Understand bubble sorting and quick sorting and JS code implementation

1. Bubble sort

principle

It is known that an array is a set of data, compare two adjacent numbers, if arr[i]>arr[i+1], exchange the positions of the two.

For example in the array [1, 4, 9, 0, 3, 7, 2]:

  • First round: 1<4, do not exchange positions; 4<9, do not exchange positions; 9>0, exchange positions of 0 and 9; 9>3, exchange positions; 9>7, exchange positions; 9>2, exchange positions Location. End the first round of sorting, the result is [1,4,0,3,7,2,9]

  • The second round: 1<4, do not exchange positions; 4>0, exchange positions; 4>3, exchange positions; 4<7, do not exchange positions; 7>2, exchange positions; 7<9, do not exchange positions. End the second round of sorting, the result is [1,0,3,4,2,7,9]

  •  Repeat the above steps, the final result is: [0,1,2,3,4,7,9]

JS implementation

        In the previous example, the comparison between 7 and 9 from the second round is actually redundant, because the largest value has been put at the end in the first round. Similarly, 4 and 7 in the third round There is no need to compare, so each time you only need to compare the index from 0 to length - 1 - i

    // 冒泡排序
    let numArr = [1, 4, 9, 0, 3, 7, 2];
    for (let i = 0; i < numArr.length - 1; i++) {
      for (let j = 0; j < numArr.length - 1 - i; j++) {
        // 如果当前元素大于后一个元素 ,交换位置
        if (numArr[j] > numArr[j + 1]) {
          numArr[j] = numArr[j] + numArr[j + 1];
          numArr[j + 1] = numArr[j] - numArr[j + 1];
          numArr[j] = numArr[j] - numArr[j + 1];
        }
      }
    }
    console.log(numArr)

2. Quick Sort

principle

        Each time a value is selected, usually the first item of the array, the value greater than the value is placed on the right, and the value smaller than the value is placed on the left. Follow this step to sort the data on the left and right respectively, and repeat this step until the sorting ends.

For example in the array [1, 4, 9, 0, 3, 7, 2]:

JS implementation

    // 快速排序
    let arr = [5, 4, 3, 1, 6, 3, 8, 7];
    function quickSort(arr, val) {
      if (arr.length <= 1) {
        return arr;
      }
      let pivot = arr[0]; // 选取基准值
      let leftArr = [];
      let rightArr = [];
      for (let i = 1; i < arr.length; i++) {
        if (arr[i] < pivot) {
          leftArr.push(arr[i]); 
        } else {
          rightArr.push(arr[i]);
        }
      }
      let leftSorted = quickSort(leftArr,'left'); // 对左侧数组进行递归排序
      let rightSorted = quickSort(rightArr,'right'); // 对右侧数组进行递归排序
      return leftSorted.concat([pivot], rightSorted); // 合并左、中、右三个数组
    }
     console.log(quickSort(arr)) 

Summarize

        This article introduces the two sorting methods of bubble sorting and quick sorting, and implements these two sorting methods with JS. If there are any mistakes, please correct me!

Guess you like

Origin blog.csdn.net/sxww_zyt/article/details/129879163