initial commit
This commit is contained in:
88
src/sorting.ts
Normal file
88
src/sorting.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { MaybeAsyncComparer } from "./async.js";
|
||||
import { reverseAsyncComparer } from "./utils.js";
|
||||
|
||||
export interface AsyncSorter {
|
||||
sort<T>(array: T[], descending: boolean, comparer: MaybeAsyncComparer<T>): Promise<void>;
|
||||
}
|
||||
|
||||
function swap(array: any[], i: number, j: number) {
|
||||
const tmp = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = tmp;
|
||||
}
|
||||
|
||||
abstract class BaseAsyncSorter implements AsyncSorter {
|
||||
async sort<T>(array: T[], descending: boolean, comparer: MaybeAsyncComparer<T>) {
|
||||
await this._sort(array, descending ? reverseAsyncComparer(comparer) : comparer);
|
||||
}
|
||||
|
||||
protected abstract _sort<T>(array: T[], comparer: MaybeAsyncComparer<T>): Promise<void>;
|
||||
}
|
||||
|
||||
class InsertionSorter extends BaseAsyncSorter {
|
||||
protected override async _sort<T>(array: T[], comparer: MaybeAsyncComparer<T>) {
|
||||
for (let i = 1; i < array.length; i++) {
|
||||
const obj = array[i];
|
||||
|
||||
for (let j = i - 1; j >= 0; j--) {
|
||||
if (await comparer(obj, array[j]) < 0) {
|
||||
for (let k = i; k > j; k--) {
|
||||
swap(array, k - 1, k);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SelectionSorter extends BaseAsyncSorter {
|
||||
protected async _sort<T>(array: T[], comparer: MaybeAsyncComparer<T>) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
let smallest = array[i];
|
||||
let smallestIndex = i;
|
||||
|
||||
for (let j = i; j < array.length; j++) {
|
||||
const current = array[j];
|
||||
|
||||
if (await comparer(current, smallest) < 0) {
|
||||
smallest = current;
|
||||
smallestIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
if (smallestIndex !== i) {
|
||||
swap(array, smallestIndex, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class BubbleSorter extends BaseAsyncSorter {
|
||||
protected async _sort<T>(array: T[], comparer: MaybeAsyncComparer<T>) {
|
||||
const length = array.length;
|
||||
|
||||
for (let k = length - 2; k >= 0; k--) {
|
||||
let hasSwaped = false;
|
||||
|
||||
for (let i = 0; i <= k; i++) {
|
||||
const j = i + 1;
|
||||
const a = array[i], b = array[j];
|
||||
|
||||
if (await comparer(a, b) > 0) {
|
||||
swap(array, i, j);
|
||||
hasSwaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasSwaped) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const insertionSorter: AsyncSorter = new InsertionSorter();
|
||||
export const selectionSorter: AsyncSorter = new SelectionSorter();
|
||||
export const bubbleSorter: AsyncSorter = new BubbleSorter();
|
||||
Reference in New Issue
Block a user