mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Swapsort algorithm and corresponding tests (#1152)
This commit is contained in:

committed by
GitHub

parent
10079a7b70
commit
32b9a9900e
31
Sorts/SwapSort.js
Normal file
31
Sorts/SwapSort.js
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* @function SwapSort
|
||||
* @description Swap Sort is an algorithm to find the number of swaps required to sort an array.
|
||||
Time complexity of Swap Sort Algorithm is O(nlogn).
|
||||
Auxiliary Space required for Swap Sort Algorithm is O(n).
|
||||
* @param {Integer[]} items - Array of integers
|
||||
* @return {Integer} - Number of swaps required to sort the array.
|
||||
* @see [SwapSort](https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/)
|
||||
*/
|
||||
|
||||
export function minSwapsToSort (items) {
|
||||
const sortedArray = items.slice()
|
||||
sortedArray.sort()
|
||||
const indexMap = {}
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
indexMap[items[i]] = i
|
||||
}
|
||||
let swaps = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (items[i] !== sortedArray[i]) {
|
||||
const temp = items[i]
|
||||
items[i] = items[indexMap[sortedArray[i]]]
|
||||
items[indexMap[sortedArray[i]]] = temp
|
||||
|
||||
indexMap[temp] = indexMap[sortedArray[i]]
|
||||
indexMap[sortedArray[i]] = i
|
||||
swaps++
|
||||
}
|
||||
}
|
||||
return swaps
|
||||
}
|
18
Sorts/test/SwapSort.test.js
Normal file
18
Sorts/test/SwapSort.test.js
Normal file
@ -0,0 +1,18 @@
|
||||
import { minSwapsToSort } from '../SwapSort'
|
||||
|
||||
describe('SwapSort', () => {
|
||||
it('should work for empty arrays', () => {
|
||||
expect(minSwapsToSort([])).toEqual(0)
|
||||
})
|
||||
|
||||
it('should work for sorted arrays', () => {
|
||||
expect(minSwapsToSort([1, 2, 3, 4, 5, 6])).toEqual(0)
|
||||
})
|
||||
|
||||
it('should return correct results', () => {
|
||||
expect(minSwapsToSort([7, 6, 2, 5, 11, 0])).toEqual(2)
|
||||
expect(minSwapsToSort([3, 3, 2, 1, 0])).toEqual(2)
|
||||
expect(minSwapsToSort([3, 0, 2, 1, 9, 8, 7, 6])).toEqual(4)
|
||||
expect(minSwapsToSort([1, 0, 14, 0, 8, 6, 8])).toEqual(3)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user