Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions sorts/swap_sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @author : dev-madhurendra<https://github.com/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 <https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/>
*/

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
}
15 changes: 15 additions & 0 deletions sorts/test/swap_sort.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});