Skip to content
This repository was archived by the owner on Mar 27, 2022. It is now read-only.

Commit 58dc53d

Browse files
committed
feat: ✨ add bubble sort function
1 parent 4c37a46 commit 58dc53d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/bubbleSort.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { CompareFunction } from './types';
2+
3+
export function bubbleSort<T>(array: T[], compare: CompareFunction<T>): T[] {
4+
const sorted = array.slice(0);
5+
let len = sorted.length ;
6+
let swapped = false;
7+
8+
for (let i = 1; i <= len - 1; i++) {
9+
swapped = false;
10+
11+
for (let j = 0; j < len - 1; j++) {
12+
if (compare(sorted[j], sorted[j + 1]) === 1) {
13+
let temp = sorted[j];
14+
sorted[j] = sorted[j + 1];
15+
sorted[j + 1] = temp;
16+
swapped = true
17+
}
18+
}
19+
20+
if (!swapped) {
21+
break;
22+
}
23+
}
24+
25+
return sorted;
26+
}

0 commit comments

Comments
 (0)