Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class QuickSort {
- constructor(array) {
- this.array = array;
- this.stack = [[0, array.length - 1]];
- }
- sort() {
- while (this.stack.length > 0) {
- const [left, right] = this.stack.pop();
- if (left >= right) {
- continue;
- }
- const pivotIndex = this.partition(left, right);
- this.stack.push([left, pivotIndex - 1]);
- this.stack.push([pivotIndex + 1, right]);
- }
- return this.array;
- }
- partition(left, right) {
- const pivot = this.array[right];
- let partitionIndex = left;
- for (let i = left; i < right; i++) {
- if (this.array[i] < pivot) {
- this.swap(i, partitionIndex);
- partitionIndex++;
- }
- }
- this.swap(right, partitionIndex);
- return partitionIndex;
- }
- swap(i, j) {
- const temp = this.array[i];
- this.array[i] = this.array[j];
- this.array[j] = temp;
- }
- }
- // Beispiel für die Verwendung der Klasse:
- const numbers = [10, 5, 3, 8, 2, 6, 4, 7, 9, 1];
- const sorter = new QuickSort(numbers);
- console.log(sorter.sort()); // gibt "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" aus
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement