diff --git a/src/structure/collections/sort.ts b/src/structure/collections/sort.ts index 5f3a78801608a9b8cdfd9c239acbf38cf0657043..0fa91e3470e45585f5bffde8b4a60b4dad37c00b 100644 --- a/src/structure/collections/sort.ts +++ b/src/structure/collections/sort.ts @@ -84,9 +84,24 @@ function partitionArrayAsc(data: number[], parts: number[], l: number, r: number parts[1] = tail; } +function insertionSort({ data, cmp, swap }: Ctx, start: number, end: number) { + for (let i = start + 1; i <= end; i++) { + let j = i - 1; + while (j >= start && cmp(data, j, j + 1) > 0) { + swap(data, j, j + 1); + j = j - 1; + } + } +} + function quickSort(ctx: Ctx, low: number, high: number) { const { parts } = ctx; while (low < high) { + if (high - low < 16) { + insertionSort(ctx, low, high); + return; + } + partitionGeneric(ctx, low, high); const li = parts[0], ri = parts[1]; @@ -100,11 +115,11 @@ function quickSort(ctx: Ctx, low: number, high: number) { } } -function insertionSort(data: number[], start: number, end: number) { +function insertionSortArrayAsc(data: number[], start: number, end: number) { for (let i = start + 1; i <= end; i++) { const key = data[i]; let j = i - 1; - while (j >= 0 && data[j] > key) { + while (j >= start && data[j] > key) { data[j + 1] = data[j]; j = j - 1; } @@ -115,7 +130,7 @@ function insertionSort(data: number[], start: number, end: number) { function quickSortArrayAsc(data: number[], parts: number[], low: number, high: number) { while (low < high) { if (high - low < 16) { - insertionSort(data, low, high); + insertionSortArrayAsc(data, low, high); return; } diff --git a/src/structure/spec/collections.spec.ts b/src/structure/spec/collections.spec.ts index 6ade6097f5318dee12ed28276ba8a62badbaebdd..d3b4489d874b7a52854575aece46879a003c6372 100644 --- a/src/structure/spec/collections.spec.ts +++ b/src/structure/spec/collections.spec.ts @@ -50,7 +50,8 @@ function shuffleArray(data: any[]) { } describe('qsort-array asc', () => { - const data0 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + const data0 = new Array(50); + for (let i = 0; i < data0.length; i++) data0[i] = i; const data1 = [1, 1, 2, 2, 3, 3, 4, 4, 4, 6, 6, 6]; function test(name: string, data: any[], randomize: boolean) { @@ -72,7 +73,8 @@ describe('qsort-array asc', () => { }) describe('qsort-array generic', () => { - const data0 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + const data0 = new Array(50); + for (let i = 0; i < data0.length; i++) data0[i] = i; const data1 = [1, 1, 2, 2, 3, 3, 4, 4, 4, 6, 6, 6]; function test(name: string, data: any[], randomize: boolean) {