Skip to content

Commit 5289b2c

Browse files
author
Oskar Widmark
committed
fix: average sort for arrays with same elements
1 parent ffbc214 commit 5289b2c

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

src/App.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,10 @@ class App extends React.Component<Props> {
273273
return arr[i1].value <= value;
274274
case '>=':
275275
return arr[i1].value >= value;
276+
case '==':
277+
return arr[i1].value == value;
278+
case '!=':
279+
return arr[i1].value != value;
276280
}
277281
}
278282

src/sorting-algorithms.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -563,15 +563,33 @@ public async mergeSort(arr, start, end){
563563
public async _averageSort(arr: SortValue[], start: number, end: number) {
564564
if (end - start <= 1) return;
565565

566+
let isUniform = true;
567+
for (let i = start; i < end; i++) {
568+
if (await this.context.compare(arr, start, '!=', i)) {
569+
isUniform = false;
570+
break;
571+
}
572+
}
573+
if (isUniform) {
574+
return;
575+
}
576+
566577
let sum = 0;
567578
for (let i = start; i < end; i++) {
568-
// for highlighting and counting comparison
579+
// for highlighting
569580
// TODO: replace
570-
await this.context.valueCompare(arr, i, '>', 0);
581+
await this.context.registerAuxWrite(arr, i);
571582
sum += arr[i].value;
572583
}
573584
const avg = sum / (end - start);
574-
const mid = Math.floor((start + end) / 2);
585+
586+
// Pick mid as the first index where arr[mid] >= avg
587+
let mid = start;
588+
for (let i = start; i < end; i++) {
589+
if (await this.context.valueCompare(arr, i, '<', avg)) {
590+
mid++;
591+
}
592+
}
575593

576594
let j = start;
577595
for (let i = mid; i < end; i++) {

src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export enum ResetPreset {
4141

4242
export type ResetFunction = () => void;
4343

44-
export type Operator = '<' | '>' | '<=' | '>=';
44+
export type Operator = '<' | '>' | '<=' | '>=' | '==' | '!=';
4545

4646
export type DrawData = {
4747
index: number;

0 commit comments

Comments
 (0)