Skip to content

Commit 7dda0e7

Browse files
dev-madhurendramadhuredraraklaptudirm
authored
feat: swap sort (TheAlgorithms#171)
--------- Co-authored-by: madhuredra <[email protected]> Co-authored-by: Rak Laptudirm <[email protected]>
1 parent 6be6a4b commit 7dda0e7

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

sorts/swap_sort.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @author : dev-madhurendra<https://github.com/dev-madhurendra>
3+
* @description
4+
* Swap Sort is an algorithm to find the number of swaps required to sort an array.
5+
* @param {number[]} inputArr - Array of numbers
6+
* @return {number} - Number of swaps required to sort the array.
7+
* @see <https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/>
8+
*/
9+
10+
export const minSwapsToSort = (inputArr: number[]): number => {
11+
const sortedArray = inputArr.slice()
12+
13+
sortedArray.sort()
14+
15+
let indexMap = new Map();
16+
17+
for (let i = 0; i < inputArr.length; i++)
18+
indexMap.set(inputArr[i],i);
19+
20+
let swaps = 0
21+
for (let i = 0; i < inputArr.length; i++) {
22+
if (inputArr[i] !== sortedArray[i]) {
23+
const temp = inputArr[i]
24+
inputArr[i] = inputArr[indexMap.get(sortedArray[i])]
25+
inputArr[indexMap.get(sortedArray[i])] = temp
26+
indexMap.set(temp,indexMap.get(sortedArray[i]))
27+
indexMap.set(sortedArray[i],1)
28+
swaps++
29+
}
30+
}
31+
32+
return swaps
33+
}

sorts/test/swap_sort.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { minSwapsToSort } from "../swap_sort";
2+
3+
describe('SwapSort', () => {
4+
it.each([
5+
{ input: [], expected: 0 },
6+
{ input: [1, 2, 3, 4, 5, 6], expected: 0 },
7+
{ input: [7, 6, 2, 5, 11, 0], expected: 2 },
8+
{ input: [3, 3, 2, 1, 0], expected: 2 },
9+
{ input: [3, 0, 2, 1, 9, 8, 7, 6], expected: 4 },
10+
{ input: [1, 0, 14, 0, 8, 6, 8], expected: 3 },
11+
])('should work for given input', ({ input, expected }) => {
12+
expect(minSwapsToSort(input)).toEqual(expected);
13+
});
14+
});
15+

0 commit comments

Comments
 (0)