frontEnd_book icon indicating copy to clipboard operation
frontEnd_book copied to clipboard

冒泡排序如何实现,时间复杂度是多少, 还可以如何改进?

Open hanyueqiang opened this issue 4 years ago • 0 comments

let arr = [2, 34, 5, 2, 1, 67, 8, 9, 37, 16];

    function sort(arr) {
      let length = arr.length;
      for (let i = 0; i < length - 1; i++) {
        for (let j = 0; j < length - 1 - i; j++) {
          if (arr[j] > arr[j + 1]) {
            let temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
          }
        }
      }
      return arr;
    }
    console.log(sort(arr)); // [1, 2, 2, 5, 8, 9, 16, 34, 37, 67]

时间复杂度O:(n**2)

hanyueqiang avatar Nov 14 '20 14:11 hanyueqiang