|
| 1 | +## Exercise |
| 2 | + |
| 3 | +Implement QuickSort Using TypeScript Generics |
| 4 | + |
| 5 | +## Solution |
| 6 | + |
| 7 | +```ts |
| 8 | + |
| 9 | +type SortPredicate = (item: Sortable) => boolean; |
| 10 | + |
| 11 | +interface Sortable { |
| 12 | + equals: SortPredicate; |
| 13 | + lessThan: SortPredicate; |
| 14 | + greaterThan: SortPredicate; |
| 15 | +} |
| 16 | + |
| 17 | +function genericPartition<T extends Sortable>( |
| 18 | + sourceArray: T[], |
| 19 | + leftIndex: number = 0, |
| 20 | + rightIndex: number = sourceArray.length - 1) { |
| 21 | + |
| 22 | + const pivotItem: T = sourceArray[Math.floor((rightIndex + leftIndex) / 2)]; |
| 23 | + |
| 24 | + let i = leftIndex; |
| 25 | + let j = rightIndex; |
| 26 | + |
| 27 | + while (i <= j) { |
| 28 | + |
| 29 | + while (sourceArray[i].lessThan(pivotItem)) { |
| 30 | + i++; |
| 31 | + } |
| 32 | + |
| 33 | + while (sourceArray[j].greaterThan(pivotItem)) { |
| 34 | + j--; |
| 35 | + } |
| 36 | + |
| 37 | + if (i <= j) { |
| 38 | + [sourceArray[i], sourceArray[j]] = [sourceArray[j], sourceArray[i]]; |
| 39 | + i++; |
| 40 | + j--; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return i; |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +function genericQuickSort<T extends Sortable>( |
| 49 | + array: T[], |
| 50 | + left: number = 0, |
| 51 | + right: number = array.length - 1) { |
| 52 | + |
| 53 | + let index: number; |
| 54 | + |
| 55 | + if (array.length > 1) { |
| 56 | + index = genericPartition<T>(array, left, right); |
| 57 | + |
| 58 | + if (left < index - 1) { |
| 59 | + genericQuickSort<T>(array, left, index - 1); |
| 60 | + } |
| 61 | + |
| 62 | + if (index < right) { |
| 63 | + genericQuickSort<T>(array, index, right); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return array; |
| 68 | +} |
| 69 | + |
| 70 | +class Cat implements Sortable { |
| 71 | + |
| 72 | + public Name: string; |
| 73 | + public Age: number; |
| 74 | + |
| 75 | + constructor(catName: string, catAge: number) { |
| 76 | + this.Name = catName; |
| 77 | + this.Age = catAge; |
| 78 | + } |
| 79 | + |
| 80 | + public equals(testCat: Cat) { |
| 81 | + return testCat.Name === this.Name; |
| 82 | + } |
| 83 | + public lessThan(testCat: Cat) { |
| 84 | + return testCat.Name > this.Name; |
| 85 | + } |
| 86 | + public greaterThan(testCat: Cat) { |
| 87 | + return testCat.Name < this.Name; |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +const unsortedArray = [ |
| 92 | + new Cat("Marvin", 4), |
| 93 | + new Cat("Arial", 3), |
| 94 | + new Cat("Felix", 3), |
| 95 | + new Cat("Tommy Boy", 9), |
| 96 | + new Cat("Athena", 1) |
| 97 | +]; |
| 98 | + |
| 99 | +const sortedArray = [...unsortedArray]; |
| 100 | + |
| 101 | +genericQuickSort<Cat>(sortedArray); |
| 102 | + |
| 103 | +console.log({unsorted: unsortedArray, sorted: sortedArray}); |
| 104 | + |
| 105 | +``` |
| 106 | + |
| 107 | +Result: |
| 108 | + |
| 109 | +<img src="../images/generic_quicksort_output.jpg"/> |
| 110 | + |
0 commit comments