Guest User

Untitled

a guest
Feb 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. /**
  2. Generic quicksort function using typescript generics.
  3. Follows quicksort as done CLRS.
  4. */
  5.  
  6. //Type-alias
  7. export type Comparator<T> = (o1: T, o2: T) => number;
  8.  
  9.  
  10. export function quickSort<T>(array: T[], compare: Comparator<T>){
  11. if(array.length <= 1 || array == null){
  12. return;
  13. }
  14. sort(array, compare, 0, array.length-1);
  15. }
  16.  
  17. function sort<T>(array: T[], compare: Comparator<T>, low: number, high: number) {
  18. if (low < high){
  19. const partIndex = partition(array, compare, low, high);
  20. sort(array, compare, low, partIndex-1);
  21. sort(array, compare, partIndex+1, high);
  22. }
  23. }
  24.  
  25. function partition<T>(array: T[], compare: Comparator<T>, low: number, high: number): number{
  26. const pivot:T = array[high];
  27. let i:number = low - 1;
  28. for(let j = low; j<=high-1; j++){
  29. if(compare(array[j], pivot) == -1){
  30. i = i + 1;
  31. swap(array, i, j)
  32. }
  33. }
  34. if(compare(array[high], array[i+1]) == -1){
  35. swap(array, i+1, high);
  36. }
  37. return i+1;
  38. }
  39.  
  40. function swap<T>(array: T[], i: number, j:number){
  41. const newJ: T = array[i];
  42. array[i] = array[j];
  43. array[j] = newJ;
  44. }
  45.  
  46. export function testQuickSort(): void{
  47.  
  48. function numberComparator(o1: number, o2: number): number {
  49. if(o1 < o2){
  50. return -1;
  51. }else if(o1 == o2){
  52. return 0;
  53. }
  54. return 1;
  55.  
  56. }
  57. let tests: number[][] = [ [], [1], [2, 1], [-1, 2, -3], [3, 16, 8, -5, 6, 4], [1,2,3,4,5,6], [1,2,3,4,5] ];
  58.  
  59. /** Iterator syntax: of is the element, in is the index **/
  60. for(let testArray of tests){
  61. quickSort(testArray, numberComparator);
  62. console.log(testArray);
  63. }
  64.  
  65.  
  66. }
Add Comment
Please, Sign In to add comment