From ab7d1d3e65bb20be2bf93b9b20caff92a1858dab Mon Sep 17 00:00:00 2001 From: madhuredra Date: Tue, 3 Oct 2023 12:16:30 +0530 Subject: [PATCH 1/2] feat : added swap sort algorithm --- sorts/swap_sort.ts | 37 ++++++++++++++++++++++++++++++++++++ sorts/test/swap_sort.test.ts | 15 +++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 sorts/swap_sort.ts create mode 100644 sorts/test/swap_sort.test.ts diff --git a/sorts/swap_sort.ts b/sorts/swap_sort.ts new file mode 100644 index 00000000..1558540a --- /dev/null +++ b/sorts/swap_sort.ts @@ -0,0 +1,37 @@ +/** + * @author : dev-madhurendra + * @description + * Swap Sort is an algorithm to find the number of swaps required to sort an array. + * @param {number[]} inputArr - Array of numbers + * @return {number} - Number of swaps required to sort the array. + * @see + */ + +export const minSwapsToSort = (inputArr: number[]): number => { + const sortedArray = inputArr.slice() + + sortedArray.sort() + + let indexMap = new Map(); + + for (let i = 0; i < inputArr.length; i++) + indexMap.set(inputArr[i],i); + + let swaps = 0 + for (let i = 0; i < inputArr.length; i++) { + if (inputArr[i] !== sortedArray[i]) { + const temp = inputArr[i] + + inputArr[i] = inputArr[indexMap.get(sortedArray[i])] + + inputArr[indexMap.get(sortedArray[i])] = temp + + indexMap.set(temp,indexMap.get(sortedArray[i])) + + indexMap.set(sortedArray[i],1) + + swaps++ + } + } + return swaps +} \ No newline at end of file diff --git a/sorts/test/swap_sort.test.ts b/sorts/test/swap_sort.test.ts new file mode 100644 index 00000000..5221f57b --- /dev/null +++ b/sorts/test/swap_sort.test.ts @@ -0,0 +1,15 @@ +import { minSwapsToSort } from "../swap_sort"; + +describe('SwapSort', () => { + it.each([ + { input: [], expected: 0 }, + { input: [1, 2, 3, 4, 5, 6], expected: 0 }, + { input: [7, 6, 2, 5, 11, 0], expected: 2 }, + { input: [3, 3, 2, 1, 0], expected: 2 }, + { input: [3, 0, 2, 1, 9, 8, 7, 6], expected: 4 }, + { input: [1, 0, 14, 0, 8, 6, 8], expected: 3 }, + ])('should work for given input', ({ input, expected }) => { + expect(minSwapsToSort(input)).toEqual(expected); + }); + }); + \ No newline at end of file From ee5ac4914ee576b540cbb34f669ec49a03c35b70 Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Wed, 4 Oct 2023 09:57:34 +0530 Subject: [PATCH 2/2] chore: fix empty lines --- sorts/swap_sort.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/sorts/swap_sort.ts b/sorts/swap_sort.ts index 1558540a..68a83ced 100644 --- a/sorts/swap_sort.ts +++ b/sorts/swap_sort.ts @@ -21,17 +21,13 @@ export const minSwapsToSort = (inputArr: number[]): number => { for (let i = 0; i < inputArr.length; i++) { if (inputArr[i] !== sortedArray[i]) { const temp = inputArr[i] - inputArr[i] = inputArr[indexMap.get(sortedArray[i])] - inputArr[indexMap.get(sortedArray[i])] = temp - indexMap.set(temp,indexMap.get(sortedArray[i])) - indexMap.set(sortedArray[i],1) - swaps++ } } + return swaps -} \ No newline at end of file +}