diff --git a/Sorts/PatienceSort.js b/Sorts/PatienceSort.js new file mode 100644 index 0000000000..67d604ef1f --- /dev/null +++ b/Sorts/PatienceSort.js @@ -0,0 +1,37 @@ +/* + * Patience Sort is a sorting algorithm inspired by, and named after, the card game patience. + * more information: https://en.wikipedia.org/wiki/Patience_sorting + */ + +export function patienceSort (items) { + const piles = [] + + for (let i = 0; i < items.length; i++) { + const num = items[i] + const destinationPileIndex = piles.findIndex( + (pile) => num >= pile[pile.length - 1] + ) + if (destinationPileIndex === -1) { + piles.push([num]) + } else { + piles[destinationPileIndex].push(num) + } + } + + for (let i = 0; i < items.length; i++) { + let destinationPileIndex = 0 + for (let p = 1; p < piles.length; p++) { + const pile = piles[p] + if (pile[0] < piles[destinationPileIndex][0]) { + destinationPileIndex = p + } + } + const distPile = piles[destinationPileIndex] + items[i] = distPile.shift() + if (distPile.length === 0) { + piles.splice(destinationPileIndex, 1) + } + } + + return items +} diff --git a/Sorts/test/PatienceSort.test.js b/Sorts/test/PatienceSort.test.js new file mode 100644 index 0000000000..ce6746dfcb --- /dev/null +++ b/Sorts/test/PatienceSort.test.js @@ -0,0 +1,25 @@ +import { patienceSort } from '../PatienceSort' + +test('The PatienceSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]', () => { + const arr = [5, 4, 3, 2, 1] + const res = patienceSort(arr) + expect(res).toEqual([1, 2, 3, 4, 5]) +}) + +test('The PatienceSort of the array [] is []', () => { + const arr = [] + const res = patienceSort(arr) + expect(res).toEqual([]) +}) + +test('The PatienceSort of the array [15, 24, 31, 42, 11] is [11, 15, 24, 31, 42]', () => { + const arr = [15, 24, 31, 42, 11] + const res = patienceSort(arr) + expect(res).toEqual([11, 15, 24, 31, 42]) +}) + +test('The PatienceSort of the array [121, 190, 169] is [121, 169, 190]', () => { + const arr = [121, 190, 169] + const res = patienceSort(arr) + expect(res).toEqual([121, 169, 190]) +})