Whats wrong with this QuickSort implementation? - java

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

Related

I implemented this merge sort algorithm into java and it didn't work

This my introductory course to Algorithms, and I understand algorithms and I can design them, but this is the first time I tryed to apply it in java code, please tell me what i did wrong in this code for it to not work properly
I'm trying to apply this algorithm ,
this is the rest of the algorithm
This is my main void:
int[] A = { 5, 2, 4, 7, 1, 3, 2, 6 };
int p = 1;
int r = A.length;
Main obi = new Main ();
obi.mergeSort (A, p, r);
my first function:
public void mergeSort (int[]A, int p, int r) {
if (p < r){
int q = (p + r) / 2;
mergeSort (A, p, q);
mergeSort (A, q + 1, r);
merge (A, p, q, r);
}
}
my second function:
public void merge (int[]A, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; i++){
L[i] = A[p + i - 1];
}
for (int j = 0; j < n2; j++){
R[j] = A[q + j];
}
int i = 0;
int j = 0;
for (int k = p - 1; k < r; k++){
if (L[i] <= R[j]){
A[k] = L[i];
i = i + 1;
} else {
A[k] = R[j];
j = j + 1;
}
}
}
And this is the error message I got:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.merge(Main.java:44)
at Main.mergeSort(Main.java:19)
at Main.mergeSort(Main.java:17)
at Main.mergeSort(Main.java:17)
at Main.main(Main.java:10)
I tried to let L[] and R[] have length n1+1 and n2+1 but it didn't help.
There are multiple problems in your code:
the arguments r and q should be the index of the first element in the slice, hence int p = 0; in main() instead of 1, and the index past the last element in the slice, hence correctly int r = A.length;
With this convention, there is no need for confusing and error prone +1/-1 adjustments in the merge and mergeSort methods.
Furthermore, the merging loop in merge should be modified to avoid accessing L[i] or R[j] when the corresponding index reaches the length of the array.
Here is a modified version:
...
int[] A = { 5, 2, 4, 7, 1, 3, 2, 6 };
int p = 0;
int r = A.length;
Main obi = new Main();
obi.mergeSort(A, p, r);
...
public void mergeSort(int[]A, int p, int r) {
if (r - p > 1) {
int q = p + (r - p) / 2;
mergeSort(A, p, q);
mergeSort(A, q, r);
merge(A, p, q, r);
}
}
public void merge(int[]A, int p, int q, int r) {
int n1 = q - p;
int n2 = r - q;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; i++) {
L[i] = A[p + i];
}
for (int j = 0; j < n2; j++) {
R[j] = A[q + j];
}
int i = 0;
int j = 0;
for (int k = p; k < r; k++) {
if (i < n1 && (j >= n2 || L[i] <= R[j])) {
A[k] = L[i];
i = i + 1;
} else {
A[k] = R[j];
j = j + 1;
}
}
}
Note that the merge method can be simplified as the elements of the second half never get overwritten before they are moved into their final spot, so there is no need to save them:
public void merge(int[]A, int p, int q, int r) {
int n1 = q - p;
int L[] = new int[n1];
for (int i = 0; i < n1; i++) {
L[i] = A[p + i];
}
int i = 0;
int j = q;
int k = p;
while (i < n1) {
if (j >= r || L[i] <= A[j])
A[k++] = L[i++];
else
A[k++] = A[j++];
}
}
Either L or R finishes first.
for (int k = p - 1; k < r; k++){
if (L[i] <= R[j]){
A[k] = L[i];
i = i + 1;
} else {
A[k] = R[j];
j = j + 1;
}
}
Lets say L finishes first then i becomes L.length+1 so that when the next iteration occurs L[i] is invalid as its one past the end.

How to fix ArrayIndexOutOfBoundsException for a Merge sort method?

So the problem that I am running into is that I am trying to get my merge sort implementation to run, but I keep getting an Exception error that says the Array index is out of bounds. This is a runtime error because I am able to compile the program with no issues and it will run up until it hits my merge sort call. One thing that I tried was changing one of my variables to match the other within the merge method (int k = 0; //line 39). When I did this, the code ran, however, the merge sorted array was not correct. I even tried debugging the code, but couldn't see an issue with it. Below is my code:
public static void merge_sort(int A[], int l, int r){
if(l < r){
int m = (l + r)/2;
merge_sort(A, l, m);
merge_sort(A, m + 1, r);
merge(A, l, m, r);//Line17
}
}
public static void merge(int A[], int l, int m, int r){
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for(int i = 0; i < n1; i++){
L[i] = A[l + i];
}
for(int j = 0; j < n2; j++){
R[j] = A[m + 1 + j];
}
int i = 0;
int j = 0;
int k = 1; //line39
while(i < n1 && j < n2){
if(L[i] <= R[j]){
A[k] = L[i];
i++;
}
else{
A[k] = R[j];
j++;
}
k++;
}
while(i < n1){
A[k] = L[i];
i++;
k++;
}
while(j < n2){
A[k] = R[j]; //line60
j++;
k++;
}
}
And here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at HW3.merge(HW3.java:60)
at HW3.merge_sort(HW3.java:17)
at HW3.main(HW3.java:160) //this line is where I call the method within the main
I understand that this means that the array is going out of the set size of 15 but I am unsure of how to fix this issue. I have tried looking at similar problems, but I did not see a solution to the issue I was having.
Everything else is fine in your code.
Except for this line
int k = 1; //line39
this should be k = l (The letter 'L' in small caps)
You can refer the following code
public class StackExchange {
public static
void mergeSort(int A[], int l , int r) {
if (l < r) {
int m = (l+r)/2;
mergeSort(A, l , m);
mergeSort(A, m+1, r);
merge(A, l, m, r);
}
}
private static void merge(int[] A, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0 ; i < n1; i++) {
L[i] = A[l+i];
}
for (int j = 0 ; j < n2; j++) {
R[j] = A[m + 1 + j];
}
int i = 0, j = 0 , k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
} else {
A[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
A[k] = L[i];
i++;
k++;
}
while (j < n2) {
A[k] = R[j];
j++;
k++;
}
}
public static void main (String...s) {
int array[] = new int[] {12, 21, 32, 36, 14, 10, 11, 5, 55, 16, 31, 7, 57, 89, 78};
mergeSort(array, 0, array.length - 1);
printArray(array);
}
private static void printArray(int array[]) {
for (int i : array) {
System.out.println(i + " -- ");
}
}
}
How are you calling your function ? Make sure that you are using object.sort(arr, 0, A.length-1); in main when you pass the max value of the array index.
here example
// Initial index of merged subarry array
int k = l; //this is L not a 1

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++];
}
}

bug in java quicksort algorithm implementation

somehow the last element of my input does not get sorted with the list i am feeding to the quicksort method
for example
input : 5,7,3,2,7,8,9,0,3,1,2,3
result: 0 1 2 2 3 3 5 7 7 8 9 3
input: 5,4,2,12,9,4
result: 2 4 5 9 12 4
any ideas where i am going wrong?
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j < list.length - 1; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}
edit
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j <= q; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}
Your for loop "skips" the last element:
for (int j = p + 1; j < list.length - 1; j++)
Modify it like this:
for (int j = p + 1; j < list.length; j++)
Btw it should be not be list.length because that way you're doing unnecessary work. You're supposed to work on the [p..q] (both inclusive) range and not on the whole array, so this is enough:
for (int j = p + 1; j <= q; j++)
You're implementation (even though it works) looks atypical. Take a look at Quicksort.

Where are comparisons in java sorting methods?

Question: Where are comparisons being made in each separate sorting method?
Also if you know please tell me which method count numbers are wrong and where to place my counters instead.trying to understand where and how many times sorting methods make comparisons.
Method A B
Selection 4950 4950
Bubble 99 9900
Insertion 99 5049
Merge 712 1028
Shell 413 649
Quick 543 1041
Okay so to explain some parts, basically Array A is an array from 1-100 in ascending order. So this should be the minimum number of comparisons.
Array B is 100-1 in descending order. So I believe it should be the maximum number of comparisons. Array C is just randomly generated numbers, so it changes every time.
I feel like my selection and bubble sorts were counted correctly. Feel free to let me know where comparisons are being made that I haven't counted, or if I'm counting wrong comparisons.
Side note: Made some global variable to count the methods that were recursive in multiple sections.
class Sorting
{
static int[] X = new int[100];
static int mergecount = 0;
static int quickcount = 0;
public static void selectionSort(int list[])
{
int count = 0;
int position = 0, n = list.length;
for(int j = 0; j < n-1; j++)
{
position = j;
for(int k = j+1; k < n; k++)
{
count++;
if(list[k] < list[position])
position = k;
}
Swap(list, j, position);
}
System.out.println("counter" + count);
}
public static void Swap(int list[], int j, int k)
{
int temp = list[j];
list[j] = list[k];
list[k] = temp;
}
public static void bubbleSort(int list[])
{
int count = 0;
boolean changed = false;
do
{
changed = false;
for(int j = 0; j < list.length - 1; j++)
{
count++;
if(list[j] > list[j + 1])
{
Swap(list, j, j+1);
changed = true;
}
}
} while(changed);
System.out.println("counter" + count);
}
public static void insertionSort(int list[])
{
int count = 0;
for(int p = 1; p < list.length; p++)
{
int temp = list[p];
int j = p;
count++;
for( ; j > 0 && temp < list[j - 1]; j = j-1)
{
list[j] = list[j - 1];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void mergeSort(int list[])
{
mergeSort(list, 0, list.length - 1);
System.out.println("counter" + mergecount);
}
public static void mergeSort(int list[], int first, int last)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(list, first, mid);
mergeSort(list, mid + 1, last);
Merge(list, first, mid, last);
}
}
public static void Merge(int list[], int first, int mid, int last)
{
int count = 0;
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int temp[] = new int[list.length];
int index = first1;
while(first1 <= last1 && first2 <= last2)
{
if(list[first1] < list[first2])
{
temp[index] = list[first1++];
mergecount++;
}
else
temp[index] = list[first2++];
index++;
mergecount++;
}
while(first1 <= last1)
temp[index++] = list[first1++];
while(first2 <= last2)
temp[index++] = list[first2++];
for(index = first; index <= last; index++)
list[index] = temp[index];
}
public static void shellSort(int list[])
{
int count = 0;
int n = list.length;
for(int gap = n / 2; gap > 0; gap = gap == 2 ? 1: (int) (gap/2.2))
for(int i = gap; i < n; i++)
{
int temp = list[i];
int j = i;
count++;
for( ; j >= gap && (temp < (list[j - gap])); j -= gap)
{
list[j] = list[j - gap];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void quickSort(int start, int finish, int list[])
{
int count = 0;
int left = start, right = finish, pivot, temp;
pivot = list[(start + finish) / 2];
do
{
while(list[left] < pivot)
{
left++;
quickcount++;
}
while(pivot < list[right])
{
right--;
quickcount++;
}
if(left <= right)
{
temp = list[left];
list[left++] = list[right];
list[right--] = temp;
quickcount++;
}
} while(left < right);
if(start < right)
quickSort(start, right, list);
if(left < finish)
quickSort(left, finish, list);
}
public static void copy(int list[])
{
for(int i = 0; i < list.length; i++)
X[i] = list[i];
}
public static void restore(int list[])
{
for(int i = 0; i < list.length; i++)
list[i] = X[i];
}
public static void displayArray(int list[])
{
for(int k = 0; k < list.length; k++)
System.out.print(list[k] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] A = new int[100];
for(int i = 0; i < A.length; i++)
A[i] = i + 1;
int[] B = new int[100];
int q = 100;
for(int i = 0; i < B.length; i++)
B[i] = q--;
int[] C = new int[100];
for(int i = 0; i < C.length; i++)
C[i] = (int)(Math.random() * 100 + 1);
displayArray(A);
copy(A);
selectionSort(A);
displayArray(A);
restore(A);
}
Note that QuickSort performance is greatly influenced by your choice of the pivot. With both of your test arrays sorted (ascending / descending) and because you are picking pivot as array[length/2] you are actually always picking the best pivot. So your test case B won't generate maximum number of comparisons for quicksort. If you were picking array[0] as pivot you'd get maximum number of comparisons for test case A and B.
The easiest way to count comparisons is to use a compare function and do it in there.
static int compareCount = 0;
int compareInt(int a, int b) {
compareCount++;
return a - b; // if 0 they are equal, if negative a is smaller, if positive b is smaller
}
Now just use compareInt in all your algorithms and you'll get an accurate count. You'll have to reset compareCount between each run though.

Categories