Skip to content

Commit 32b9a99

Browse files
authored
Swapsort algorithm and corresponding tests (TheAlgorithms#1152)
1 parent 10079a7 commit 32b9a99

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Sorts/SwapSort.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @function SwapSort
3+
* @description Swap Sort is an algorithm to find the number of swaps required to sort an array.
4+
Time complexity of Swap Sort Algorithm is O(nlogn).
5+
Auxiliary Space required for Swap Sort Algorithm is O(n).
6+
* @param {Integer[]} items - Array of integers
7+
* @return {Integer} - Number of swaps required to sort the array.
8+
* @see [SwapSort](https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/)
9+
*/
10+
11+
export function minSwapsToSort (items) {
12+
const sortedArray = items.slice()
13+
sortedArray.sort()
14+
const indexMap = {}
15+
for (let i = 0; i < items.length; i++) {
16+
indexMap[items[i]] = i
17+
}
18+
let swaps = 0
19+
for (let i = 0; i < items.length; i++) {
20+
if (items[i] !== sortedArray[i]) {
21+
const temp = items[i]
22+
items[i] = items[indexMap[sortedArray[i]]]
23+
items[indexMap[sortedArray[i]]] = temp
24+
25+
indexMap[temp] = indexMap[sortedArray[i]]
26+
indexMap[sortedArray[i]] = i
27+
swaps++
28+
}
29+
}
30+
return swaps
31+
}

Sorts/test/SwapSort.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { minSwapsToSort } from '../SwapSort'
2+
3+
describe('SwapSort', () => {
4+
it('should work for empty arrays', () => {
5+
expect(minSwapsToSort([])).toEqual(0)
6+
})
7+
8+
it('should work for sorted arrays', () => {
9+
expect(minSwapsToSort([1, 2, 3, 4, 5, 6])).toEqual(0)
10+
})
11+
12+
it('should return correct results', () => {
13+
expect(minSwapsToSort([7, 6, 2, 5, 11, 0])).toEqual(2)
14+
expect(minSwapsToSort([3, 3, 2, 1, 0])).toEqual(2)
15+
expect(minSwapsToSort([3, 0, 2, 1, 9, 8, 7, 6])).toEqual(4)
16+
expect(minSwapsToSort([1, 0, 14, 0, 8, 6, 8])).toEqual(3)
17+
})
18+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy