-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.js
More file actions
34 lines (30 loc) · 900 Bytes
/
sort.js
File metadata and controls
34 lines (30 loc) · 900 Bytes
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
export async function oddEvenSort(arr, asyncCompare) {
const n = arr.length;
let sorted = false;
while (!sorted) {
sorted = true;
console.info("Sort even-indexed elements");
for (let i = 0; i < n - 1; i += 2) {
const shouldSwap = await asyncCompare(arr[i], arr[i + 1]);
if (shouldSwap > 0) {
console.info("shouldSwap");
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
sorted = false;
}
}
console.info("Sort odd-indexed elements");
for (let i = 1; i < n - 1; i += 2) {
const shouldSwap = await asyncCompare(arr[i], arr[i + 1]);
if (shouldSwap > 0) {
console.info("shouldSwap");
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
sorted = false;
}
}
}
return arr;
}
export function estimateOddEvenSortComparisons(n) {
if (n < 2) return 0;
return (n / 2) * (Math.log(n) + 0.577);
}