diff --git a/sorts/swap_sort.ts b/sorts/swap_sort.ts new file mode 100644 index 00000000..68a83ced --- /dev/null +++ b/sorts/swap_sort.ts @@ -0,0 +1,33 @@ +/** + * @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 +} 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