Implementing Wikipedia in-place quicksort pseudocode in Java - java

I'm using the pseudocode called Lomuto partition scheme on https://en.wikipedia.org/wiki/Quicksort. But I just don't understand what it is that I am doing wrong here. The array never gets organized (regardless of the input size). This is preparation for my final exam. My professor wants us to use this algorithm, but I can't just learn it unless I have an understanding of how it works by testing it.
private static void quickSort(Integer A[], int l, int r) {
if (l < r) {
int k = partition(A, l, r);
quickSort(A, l, k - 1);
quickSort(A, k + 1, r);
}
}
private static int partition(Integer A[], int l, int r) {
int pivot = A[r];
int i = l;
for (int j = l; j <= r - 1; j++) {
if (A[j] <= pivot) {
i++;
int temp = A[j];
A[j] = pivot;
pivot = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[r];
A[r] = temp;
return i + 1;
}

I don't know what else to say other than that you just didn't transcribe the pseudocode correctly. At the beginning of partition, i should equal l - 1, but you set it to l.
Also, you're not swapping A[i] with A[j] within the nested loop. Here's the correct implementation:
private static int partition(Integer A[], int l, int r) {
int pivot = A[r];
int i = l - 1;
for (int j = l; j <= r - 1; j++) {
if (A[j] < pivot) {
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[r];
A[r] = temp;
return i + 1;
}

Related

Analysis of Hoare's Partioning

I have an assignment to draw a graph and analyze the Hoare's partitioning algorithm and compare theoretical and practical worst-case scenario values. It says that I need a count variable to keep track of critical steps (i.e comparison and swapping). I wrote this code for Hoare's partitioning.
public static int partition(Comparable[] a, int left, int right) {
Comparable pivot = a[(left + right) / 2];
int i = left - 1, j = right + 1;
while (true) {
do {
i++;
} while (a[i].compareTo(pivot) < 0);
do {
j--;
} while (a[j].compareTo(pivot) > 0);
if (i < j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
} else {
return j;
}
}
}
Now I am confused about where to add the count variable. I know that count variable will be incremented in if (i < j) line. But do I also need to increment count in both do-while loops to keep track of comparisons?
So, the updated code will be like this?
public static int partition(Comparable[] a, int left, int right) {
int count = 0;
Comparable pivot = a[(left + right) / 2];
int i = left - 1, j = right + 1;
while (true) {
do {
count++;
i++;
} while (a[i].compareTo(pivot) < 0);
do {
count++;
j--;
} while (a[j].compareTo(pivot) > 0);
if (i < j) {
count++;
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
} else {
return j;
}
}
}
Or like this?
public static int partition(Comparable[] a, int left, int right) {
int count = 0;
Comparable pivot = a[(left + right) / 2];
int i = left - 1, j = right + 1;
while (true) {
do {
i++;
} while (a[i].compareTo(pivot) < 0);
do {
j--;
} while (a[j].compareTo(pivot) > 0);
if (i < j) {
count++;
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
} else {
return j;
}
}
}

Why is this test for my quick sort failing?

I'm trying to implement quicksort using the median of three algo and it fails a unit test I wrote related to a small partition. I changed my earlier partition and now it passes one of the tests it used to fail, but still fails the one at the bottom:
My code is:
public class QuickSort {
static void swap(int[] A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
static final int LIMIT = 15;
static int partition(int[] a, int left, int right){
int center = (left + right) / 2;
if(a[center] < (a[left]))
swap(a,left,center);
if(a[right-1] < a[left])
swap(a,left,right);
if(a[right-1] < a[center])
swap(a,center,right);
swap(a,center,right - 1);
return a[right - 1];
}
static void quicksort(int[] a, int left, int right){
if(left + LIMIT <= right){
int pivot = partition(a,left,right);
int i = left;
int j = right - 1;
for(;;){
while(a[++i] < pivot){}
while(a[--j] > pivot){}
if(i < j)
swap(a,i,j);
else
break;
}
swap(a,i,right - 1);
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
else{
insertionSort(a);
}
}
public static void insertionSort(int[] a){
int j;
for(int p = 1; p < a.length; p++){
int tmp = a[p];
for(j = p; j > 0 && tmp < a[j-1]; j--)
a[j] = a[j-1];
a[j] = tmp;
}
}
}
This test fails:
public void smalltest() throws Exception {
int[] Arr_orig = {3,9,8,2,4,6,7,5};
int[] Arr = Arr_orig.clone();
int pivot = QuickSort.partition(Arr, 0, Arr.length);
for (int i = 0; i != pivot; ++i)
assertTrue(Arr[i] <= Arr[pivot]); //fails!
for (int i = pivot + 1; i != Arr.length; ++i)
assertTrue(Arr[pivot] < Arr[i]);
}
There is a conflict between using right-1 and right in this sequence:
if(a[right-1] < a[left])
swap(a,left,right);
You need to decide if right is going to be the index to the last element, or 1 + index to the last element (an "ending" index).
There may be other problems, but this is the first one I noticed.

Merge sort implementation questions in Java

I'm in an algorithms course and am learning about merge sort. Our professor recommended we try to implement the pseudo code provided in the book.
Am I correct in using Integer.MAX_VALUE as a sentinel value when
sorting an array of integers (used in lines 8 & 9 in the Merge
method pseudo code below)?
For line 2 of the Merge-Sort pseudo code method, is it correct to code that in Java using Math.ceil() like I did? (Edit: It's actually floor and I updated my code to reflect this.)
If you see any other mistakes please let me know!
Here is the pseudo code the book gives for merge sort.
And, here is how I coded it in Java:
public void mergeSort(int[] arrNums, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(arrNums, p, q);
mergeSort(arrNums, q + 1, r);
merge(arrNums, p, q, r);
}
}
public void merge(int[] arrNums, int p, int q, int r) {
int nOne = q - p + 1;
int nTwo = r - q;
int[] arrLeft = new int[nOne + 1];
int[] arrRight = new int[nTwo + 1];
for (int i = 0; i < nOne; i++) {
arrLeft[i] = arrNums[p + i - 1];
}
for (int j = 0; j < nTwo; j++) {
arrRight[j] = arrNums[q + j];
}
arrLeft[nOne] = Integer.MAX_VALUE;
arrRight[nTwo] = Integer.MAX_VALUE;
// Tracks arrLeft index
int i = 0;
// Tracks arrRight index
int j = 0;
for (int k = p; k < r; k++) {
if (arrLeft[i] <= arrRight[j]) {
arrNums[k] = arrLeft[i];
i++;
} else {
arrNums[k] = arrRight[j];
j++;
}
}
}
The last for loop in your merge method, variable k should start from p - 1:
for (int k = p - 1; k < r; k++) {
if (arrLeft[i] <= arrRight[j]) {
arrNums[k] = arrLeft[i];
i++;
} else {
arrNums[k] = arrRight[j];
j++;
}
}
Pseudo code in many text books likes to start array index from 1, so here you need to subtract it by 1.
I implemented it a few days ago, if someone will be interested.
private static void mergeSort(double[] arr, int start, int end){
if(start < end){
int mid = ( start + end ) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
Merge(arr, start, mid, end);
}
}
private static void Merge(double[] arr, int start, int mid, int end){
double[] leftArray = new double[mid - start + 2];
double[] rightArray = new double[end - mid + 1];
for(int i = start; i <= mid; i++ )
leftArray[i - start] = arr[i];
for (int i = mid + 1; i <= end; i++ )
rightArray[i - mid - 1] = arr[i];
leftArray[mid - start + 1] = Double.POSITIVE_INFINITY;
rightArray[end - mid] = Double.POSITIVE_INFINITY;
int leftIndex = 0, rightIndex = 0;
for (int k = start; k <= end; k++){
if(leftArray[leftIndex] <= rightArray[rightIndex])
arr[k] = leftArray[leftIndex++];
else
arr[k] = rightArray[rightIndex++];
}
}

Whats wrong with this QuickSort implementation?

I cannot guess what is wrong with my code.
INPUT:10, 7, 8, 9, 1, 5
OUTPUT:5 7 9 8 10 1
public class QuickSort {
public static void quickSort(int arr[], int p, int r) {
if (p < r) {
// System.out.println(p+" "+r);
int q = partition(arr, p, r);
quickSort(arr, p, q - 1);
quickSort(arr, q + 1, r);
}
}
public static int partition(int arr[], int p, int r) {
int pivot = arr[r];
int i = p - 1;
for (int j = p; j < r - 1; j++) {
// System.out.println("j");
if (arr[j] <= pivot) {
i = i + 1;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[r];
arr[r] = temp;
return i + 1;
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
}
Please clarity my doubt,where to change code so that it works fine.
You are not iterating to the end of the loop (last element). Hence the partition function will not seperate the elements correctly as smaller to the left of pivot and larger to the right of pivot.
Your for loop
for (int j = p; j < r - 1; j++) {
change to
for (int j = p; j <= r - 1; j++) {
Now it is working fine.
See here Ideone

Quicksort (Java) causes StackOverFlow at array.length > 60k

My code works properly (to my knowledge) up until my input array size (a.length) is around 62,000 at which time I consistently get a StackOverFlowError. I previously had used 2 recursive calls to quicksort (less than, and greater than the pivot q) and then I switched to tail recursion. As you can see, I'm selecting the pivot to be the value at the end of the array. I know this isn't the best way to choose a pivot, but I still shouldn't be seeing StackOverFlowErrors with an array size this small, right? What could be causing this? Thanks in advance! Here's my code:
public static void quicksort(int[] a, int p, int r)
{
int q;
while (p < r)
{
q = partition(a, p, r);
quicksort(a, p, q - 1);
p = q + 1;
}
}
public static int partition(int[] a, int p, int r)
{
int j = p - 1;
int x = a[r];
for (int i = p; i < r; i++)
{
if (a[i] <= x)
{
j++;
swap(a, i, j);
}
}
j++;
swap(a, j, r);
return j;
}
private static void swap(int[] a, int i, int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
The worst-case input (sorted order) makes quicksort Θ(n^2). Partition always puts a single element on one side of the partition (Cormen et al.). By randomizing the sort (choosing a random pivot) no particular input elicits its worst-case behavior.
import java.util.Random;
public class Quicksort
{
private static Random rand = new Random();
public static void quicksort(int[] arr, int left, int right)
{
if (left < right)
{
int pivot = randomizedPartition(arr, left, right);
quicksort(arr, left, pivot);
quicksort(arr, pivot + 1, right);
}
}
private static int randomizedPartition(int[] arr, int left, int right)
{
int swapIndex = left + rand.nextInt(right - left) + 1;
swap(arr, left, swapIndex);
return partition(arr, left, right);
}
private static int partition(int[] arr, int left, int right)
{
int pivot = arr[left];
int i = left - 1;
int j = right + 1;
while (true)
{
do
j--;
while (arr[j] > pivot);
do
i++;
while (arr[i] < pivot);
if (i < j)
swap(arr, i, j);
else
return j;
}
}
private static void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// Sort 100k elements that are in reversed sorted order
public static void main(String[] args)
{
int arr[] = new int[100000];
for (int i = 0; i < arr.length; i++)
arr[i] = arr.length - i;
System.out.println("First 20 elements");
System.out.print("Before sort: ");
for (int i = 0; i < 20; i++)
System.out.print(arr[i] + " ");
System.out.println();
quicksort(arr, 0, arr.length - 1);
System.out.print("After sort: ");
for (int i = 0; i < 20; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
Given the right input, your implementation will recurse once for every single element of the array. 60,000 recursive calls could easily be enough to overflow the stack in Java in the default configuration.

Categories