|
| 1 | +/** |
| 2 | + * @function cycleSort |
| 3 | + * @description Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result. |
| 4 | + * @param {number[]}array - The input array |
| 5 | + * @return {number[]} - The sorted array. |
| 6 | + * @see [CycleSort] https://en.wikipedia.org/wiki/Cycle_sort |
| 7 | + * @example cycleSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] |
| 8 | + */ |
| 9 | + |
| 10 | +export const cycleSort = (array: number[]) => { |
| 11 | + for (let i: number = 0; i < array.length - 1; i++) { |
| 12 | + MoveCycle(array, i); |
| 13 | + } |
| 14 | + return array; |
| 15 | +}; |
| 16 | + |
| 17 | +function MoveCycle(array: number[], startIndex: number) : void { |
| 18 | + |
| 19 | + let currentItem: number = array[startIndex]; |
| 20 | + let nextChangeIndex: number = startIndex + CountSmallerItems(array, startIndex, currentItem); |
| 21 | + if(nextChangeIndex == startIndex) |
| 22 | + { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + nextChangeIndex = SkipDuplicates(array, nextChangeIndex, currentItem); |
| 27 | + |
| 28 | + let tmp: number = array[nextChangeIndex]; |
| 29 | + array[nextChangeIndex] = currentItem; |
| 30 | + currentItem = tmp; |
| 31 | + |
| 32 | + while (nextChangeIndex != startIndex) |
| 33 | + { |
| 34 | + nextChangeIndex = startIndex + CountSmallerItems(array, startIndex, currentItem); |
| 35 | + nextChangeIndex = SkipDuplicates(array, nextChangeIndex, currentItem); |
| 36 | + |
| 37 | + tmp = array[nextChangeIndex]; |
| 38 | + array[nextChangeIndex] = currentItem; |
| 39 | + currentItem = tmp; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +function CountSmallerItems(array: number[], startIndex: number, currentItem: number) : number{ |
| 44 | + let elementsCount: number = 0; |
| 45 | + |
| 46 | + for (let i: number = startIndex + 1; i < array.length; i++) { |
| 47 | + if(currentItem > array[i]) |
| 48 | + { |
| 49 | + elementsCount++; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return elementsCount; |
| 54 | +} |
| 55 | + |
| 56 | +function SkipDuplicates(array: number[], currentPosition: number, currentItem: number): number { |
| 57 | + while (array[currentPosition] == currentItem) { |
| 58 | + currentPosition++; |
| 59 | + } |
| 60 | + |
| 61 | + return currentPosition; |
| 62 | +} |
| 63 | + |
0 commit comments