Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 48 additions & 22 deletions src/main/java/algorithms/QuickSort.java
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -11,39 +14,62 @@ public QuickSort(ArrayList<Integer> 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<Integer> 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<Integer> 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;
}

}