Jason Khalili
Jason Khalili

Reputation: 101

Infinite While Loop in Quick Sort

I'm coding a quick sort in Java, and I've completed the partitioning portion, but for some reason, my program keeps running forever with:

x was swapped with x

where x is some random integer, but the same integer every time it is printed. I've tried to debug this, but it runs fine every time in the debugger. What am I doing wrong? Here's my code excluding the parent class, array generator, etc.

class QuickSort extends BasicSort {

public QuickSort() {
    super("QuickSort");
}

public void sort() {
    int pivot = data[data.length / 2];
    int low = 0, high = data.length - 1;

    while (true) {
        while (low < (data.length - 1) && data[low] < pivot) {
            System.out.println(data[low] + " is less than " + pivot);
            low++;
        }
        while (high > 0 && data[high] > pivot) {
            System.out.println(data[high] + " is greater than " + pivot);
            high--;
        }

        if (low >= high) {
            break;
        } else {
            int temp = data[low];
            data[low] = data[high];
            data[high] = temp;

            System.out.println(data[low] + " was swapped with " + data[high]);
        }
    }
}
}

Upvotes: 0

Views: 1249

Answers (1)

Jason Khalili
Jason Khalili

Reputation: 101

This is an issue with identical numbers, I have to write code for that condition. Thanks guys.

Upvotes: 1

Related Questions