IntroSort [内省排序]
# 介绍
IntroSort 首先从快速排序开始,当递归深度超过一定深度(深度为排序元素数量的对数值)后转为堆排序。采用这个方法,内省排序既能在常规数据集上实现快速排序的高性能,又能在最坏情况下仍保持 的时间复杂度。由于这两种算法都属于比较排序算法,所以内省排序也是一个比较排序算法。
# 原理
回顾 quickSort、heapSort 和 insertionSort:
- 快速排序在大多数情况下效率最高,应当是首选的排序算法。但是它在某些情况下,会掉入陷阱,复杂度恶化到 。
- 堆排序虽然在大多数情况下不如快速排序效率高,但在所有的情况下复杂度都是 。因此若能检测到快速排序掉入陷阱,则堆排序会是一个很好的补充。
- 插入排序虽然复杂度虽然只能达到 ,但若能已知「几乎已经排好序」,切换到插入排序的效率又要比快速排序和堆排序高出不少,能做到 。
# 复杂度
- 平均时间复杂度
- 最坏时间复杂度
# 实现
# JavaScript
function introSort (array, compare) {
/**
* @function Default Comparison Function
* This function is same as implemented by
* Array.sort method
* @see [StackOverflow](https://stackoverflow.com/questions/47334234/how-to-implement-array-prototype-sort-default-compare-function)
* @param {*} a variable 1
* @param {*} b variable 2
* @returns {Number}
* -1 if a is less than b
* 0 if a is equal to b
* 1 if a greater than b
*/
const defaultComparator = function (x, y) {
if (x === undefined && y === undefined) return 0
if (x === undefined) return 1
if (y === undefined) return -1
const xString = toString(x)
const yString = toString(y)
if (xString < yString) return -1
if (xString > yString) return 1
return 0
}
/**
* @function helper function for defaultComparator
* Converts a given object to String
* @throws TypeError()
* @param {Object} obj
* @returns {String} String representation of given object
*/
const toString = function (obj) {
if (obj === null) return 'null'
if (typeof obj === 'boolean' || typeof obj === 'number') {
return obj.toString()
}
if (typeof obj === 'string') return obj
if (typeof obj === 'symbol') throw new TypeError()
return obj.toString()
}
/**
* Checks if the value passed is an array
* or not
*/
if (Array.isArray(array) === false) {
return
}
/**
* If the compare parameter is not a function
* or not passed at all use default comparator
* function
*/
if (typeof compare !== 'function') {
compare = defaultComparator // If compare is not a comparator function
}
/**
* Use a closure to define the whole sort
* implementation this is done through
* [IIFE](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression)
*/
return (function (array, comparator) {
const swap = function (index1, index2) {
const temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
}
/**
* @constant THRESHOLD
* If the length of array is less than
* this then we simply perform insertion sort
*/
const THRESHOLD = 16
/**
* @constant TUNEMAXDEPTH
* Constant usec to increase or decrease value
* of maxDepth
*/
const TUNEMAXDEPTH = 1
const len = array.length
/**
* Return if array is only of length 1
* Array of size 1 is always sorted
*/
if (len === 1) {
return
}
/**
* Calculate maxDepth = log2(len)
* Taken from implementation in stdc++
*/
const maxDepth = Math.floor(Math.log2(len)) * TUNEMAXDEPTH
/**
* The very first call to quicksort
* this initiates sort routine
*/
quickSort(0, len, maxDepth)
/**
* A final check call to insertion sort
* on sorted array
*/
insertionSort(0, len)
/** ********************* Implementation of various routines **************************/
/**
* @function
* This is recursive quicksort implementation in array
* of segment [start,last-1]
* [QuickSort](https://en.wikipedia.org/wiki/Quicksort)
* @param {Number} start the start index of array segment to be sorted
* @param {Number} last one more than the last index of array segment
* @param {Number} depth this measures how many recursive calls are done
*/
function quickSort (start, last, depth) {
if (last - start <= THRESHOLD) {
insertionSort(start, last)
return
} else if (depth <= 0) {
heapSort(start, last)
return
}
let pivot = (last + start) >> 1
pivot = partition(start, last, pivot)
quickSort(start, pivot, depth - 1)
quickSort(pivot + 1, last, depth - 1)
}
/**
* @function Helper function to quicksort
* @param {Number} start the start of array segment to partition
* @param {Number} last one more than last index of the array segment
* @param {Number} pivot the index of pivot to be used
* @returns {Number} the index of pivot after partition
*/
function partition (start, last, pivot) {
swap(start, pivot)
pivot = start
let lo = start
let hi = last
while (true) {
lo++
while (comparator(array[lo], array[pivot]) <= 0 && lo !== last) {
lo++
}
hi--
while (comparator(array[hi], array[pivot]) > 0 && hi !== start) {
hi--
}
if (lo >= hi) {
break
}
swap(lo, hi)
}
swap(start, hi)
return hi
}
/**
* @function
* Performs insertion sort on array of range
* [start, last-1]
* @param {Number} start the first index of array segment to be sorted
* @param {Number} last one more than last index of array to be sorted
*/
function insertionSort (start, last) {
let i, j
for (i = start + 1; i < last; i++) {
j = i - 1
while (j >= 0 && comparator(array[j], array[j + 1]) > 0) {
swap(j, j + 1)
j--
}
}
}
/**
* @function
* Performs heapsort in array segment of range [start, last-1]
* [HeapSort](https://en.wikipedia.org/wiki/Heapsort)
* @param {Number} start the first index of array segment to be sorted
* @param {Number} last one more than last index of array to be sorted
*/
function heapSort (start, last) {
let x = (last + start) >> 1
while (x - start >= 0) {
heapify(x, start, last)
x--
}
x = last - 1
while (x - start > 0) {
swap(start, x)
heapify(start, start, x)
x--
}
}
/**
* @function Helper function to heapsort routine
* @param {Number} cur the index we need to heapify
* @param {Number} start the start index of array segment that cur belongs to
* @param {Number} last one more than last index of segment that cur belongs to
*/
function heapify (cur, start, last) {
const size = last - start
let max, lt, rt
cur = cur - start
while (true) {
max = cur
lt = 2 * max + 1
rt = 2 * max + 2
if (
lt < size &&
comparator(array[start + max], array[start + lt]) < 0
) {
max = lt
}
if (
rt < size &&
comparator(array[start + max], array[start + rt]) < 0
) {
max = rt
}
if (max !== cur) {
swap(start + cur, start + max)
cur = max
} else {
break
}
}
}
})(array, compare)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# 参考
编辑 (opens new window)
上次更新: 2022/05/06, 13:20:49