diff --git a/src/main/java/algorithms/QuickSort.java b/src/main/java/algorithms/QuickSort.java index 9970204..990439a 100644 --- a/src/main/java/algorithms/QuickSort.java +++ b/src/main/java/algorithms/QuickSort.java @@ -1,6 +1,9 @@ package algorithms; +import ui.Utils; + import java.util.ArrayList; +import java.util.HashSet; import java.util.Set; public class QuickSort extends SortingAlgorithm { @@ -11,39 +14,62 @@ public QuickSort(ArrayList array) { @Override public void sort() { - int SLEEP_DURATION = 25; - quickSort(0, array.size() - 1, sortedIndices, SLEEP_DURATION); - printArray( -1, -1); + int SLEEP_DURATION = 10; + Thread t = NewQuickSortThread(0, array.size() - 1, SLEEP_DURATION); + t.start(); + try { + t.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + printArray(-1, -1); } - void quickSort(int start, int end, Set sortedIndices, int sleepDuration) { - if (start < end) { - int pi = partition(start, end, sortedIndices, sleepDuration); - quickSort(start, pi - 1, sortedIndices, sleepDuration); - quickSort(pi + 1, end, sortedIndices, sleepDuration); - } + Thread NewQuickSortThread(int start, int end, int sleepDuration) { + return new Thread(() -> { + if (start < end) { + int pi = partition(start, end, sleepDuration); + Thread left = NewQuickSortThread(start, pi - 1, sleepDuration); + Thread right = NewQuickSortThread(pi + 1, end, sleepDuration); + + left.start(); + right.start(); + + try { + left.join(); + right.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + }); } - int partition(int start, int end, Set sortedIndices, int sleepDuration) { - int pivot = array.get(end); - int pIndex = start; + int partition(int start, int end, int sleepDuration) { + int pivotValue = array.get(end); + int partitionIndex = start; - for (int i = start; i <= end - 1; i++) { + for (int i = start; i < end; i++) { printArray(i, end); - comparisonCount++; - if (array.get(i) <= pivot) { - swapHighlighted(pIndex, i, sleepDuration); + if (array.get(i) <= pivotValue) { + swapHighlighted(partitionIndex, i, sleepDuration); swapCount++; - pIndex++; + partitionIndex++; + if (array.get(i) == pivotValue) sortedIndices.add(i); } + + comparisonCount++; } - swapHighlighted( pIndex, end, sleepDuration); + swapHighlighted( partitionIndex, end, sleepDuration); swapCount++; - sortedIndices.add(pIndex); - sortedIndices.add(start); - sortedIndices.add(end); - return pIndex; + sortedIndices.add(partitionIndex); + if (start == end - 1) { + sortedIndices.add(start); + sortedIndices.add(end); + } + + return partitionIndex; } }