How does Javascript's sort() work?

前端 未结 9 1922
长情又很酷
长情又很酷 2020-11-22 11:06

How does the following code sort this array to be in numerical order?

var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})
9条回答
  •  礼貌的吻别
    2020-11-22 11:51

    Is the array sort callback function called many times during the course of the sort?

    Since this is a comparison sort, given N items, the callback function should be invoked on average (N * Lg N) times for a fast sort like Quicksort. If the algorithm used is something like Bubble Sort, then the callback function will be invoked on average (N * N) times.

    The minimum number of invocations for a comparison sort is (N-1) and that is only to detect an already sorted list (i.e. early out in Bubble Sort if no swaps occur).

提交回复
热议问题