From 3ebfbb10b9ab8961660440bca4b18f7eb331b72e Mon Sep 17 00:00:00 2001 From: samuuka_zs <127270812+Samuelf27@users.noreply.github.com> Date: Thu, 25 Jun 2026 21:08:45 -0300 Subject: [PATCH 1/2] feat: add Comb Sort algorithm --- sorts/comb_sort.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 sorts/comb_sort.ts diff --git a/sorts/comb_sort.ts b/sorts/comb_sort.ts new file mode 100644 index 00000000..31ce9fa9 --- /dev/null +++ b/sorts/comb_sort.ts @@ -0,0 +1,32 @@ +/** + * @function combSort + * @description Comb sort improves on bubble sort by comparing elements separated by a gap that shrinks each pass (by a factor of ~1.3), removing small values stuck near the end ("turtles") much faster than bubble sort. + * @param {number[]} arr - The input array + * @return {number[]} - The sorted array. + * @see [CombSort] https://en.wikipedia.org/wiki/Comb_sort + * @example combSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] + */ + +export const combSort = (arr: number[]): number[] => { + const shrinkFactor = 1.3 + let gap = arr.length + let isSorted = false + + while (!isSorted) { + gap = Math.floor(gap / shrinkFactor) + + if (gap <= 1) { + gap = 1 + isSorted = true + } + + for (let i = 0; i + gap < arr.length; i++) { + if (arr[i] > arr[i + gap]) { + ;[arr[i], arr[i + gap]] = [arr[i + gap], arr[i]] + isSorted = false + } + } + } + + return arr +} From fd775333763ce92717c20cec0120f60500c76b78 Mon Sep 17 00:00:00 2001 From: samuuka_zs <127270812+Samuelf27@users.noreply.github.com> Date: Thu, 25 Jun 2026 21:08:46 -0300 Subject: [PATCH 2/2] test: add Comb Sort tests --- sorts/test/comb_sort.test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 sorts/test/comb_sort.test.ts diff --git a/sorts/test/comb_sort.test.ts b/sorts/test/comb_sort.test.ts new file mode 100644 index 00000000..78d99962 --- /dev/null +++ b/sorts/test/comb_sort.test.ts @@ -0,0 +1,21 @@ +import { combSort } from '../comb_sort' + +describe('Testing Comb sort', () => { + const testCases: number[][] = [ + [], + [2, 1], + [8, 3, 5, 9, 1, 7, 4, 2, 6], + [9, 8, 7, 6, 5, 4, 3, 2, 1], + [1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 1, 1, 1, 1, 1, 1, 1, 1] + ] + + test.each(testCases)( + 'should return the correct value for test case: %#', + (...arr: number[]) => { + expect(combSort([...arr])).toStrictEqual( + [...arr].sort((a: number, b: number) => a - b) + ) + } + ) +})