Advertisement
rgruber

QuickSort Class

Dec 25th, 2022
942
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.11 KB | Source Code | 0 0
  1. class QuickSort {
  2.   constructor(array) {
  3.     this.array = array;
  4.     this.stack = [[0, array.length - 1]];
  5.   }
  6.  
  7.   sort() {
  8.     while (this.stack.length > 0) {
  9.       const [left, right] = this.stack.pop();
  10.  
  11.       if (left >= right) {
  12.         continue;
  13.       }
  14.  
  15.       const pivotIndex = this.partition(left, right);
  16.       this.stack.push([left, pivotIndex - 1]);
  17.       this.stack.push([pivotIndex + 1, right]);
  18.     }
  19.  
  20.     return this.array;
  21.   }
  22.  
  23.   partition(left, right) {
  24.     const pivot = this.array[right];
  25.     let partitionIndex = left;
  26.  
  27.     for (let i = left; i < right; i++) {
  28.       if (this.array[i] < pivot) {
  29.         this.swap(i, partitionIndex);
  30.         partitionIndex++;
  31.       }
  32.     }
  33.  
  34.     this.swap(right, partitionIndex);
  35.     return partitionIndex;
  36.   }
  37.  
  38.   swap(i, j) {
  39.     const temp = this.array[i];
  40.     this.array[i] = this.array[j];
  41.     this.array[j] = temp;
  42.   }
  43. }
  44.  
  45. // Beispiel für die Verwendung der Klasse:
  46. const numbers = [10, 5, 3, 8, 2, 6, 4, 7, 9, 1];
  47. const sorter = new QuickSort(numbers);
  48. console.log(sorter.sort()); // gibt "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" aus
  49.  
Tags: Quicksort
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement