I was given an assignment to implement the following algorithm:
I am a little confused by reading the algorithm itself, I tried to follow the algorithm but, since I cannot understand it completely my code does not work. Can anyone, please, have a look at my code (this is the bit that I cannot understand what to fix):
public static void mergeSortNonRec(Comparable[] a) {
Comparable[] a1 = new Comparable[a.length];
Comparable[] b = new Comparable[a.length];
for (int i = 1; i < a.length; i *= 2) {
for (int j = 0; j < a.length; j += 2 * i) {
merge(a1, j, (Integer.min(j + i, a.length) - 1), a1, j + i, (Integer.min(j + 2 * i, a.length) - 1), b, 0);
}
}
for (int i = 0; i < a.length; i++) {
a[i] = a1[i];
}
}
This is my helper method that I have tested with my recursive mergeSort and I know it works:
private static void merge(Comparable[] a1, int left1, int right1, Comparable[] a2, int left2, int right2, Comparable[] a, int left) {
int i = left1;
int j = left2;
int k = left;
while (i <= right1 && j <= left2) {
int comp = a1[i].compareTo(a2[j]);
if (comp <= 0) {
a[k++] = a1[i++];
} else {
a[k++] = a2[j++];
}
}
while (i <= right1) {
a[k++] = a1[i++];
}
while (j <= right2) {
a[k++] = a2[j++];
}
}
Related
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
I am trying make an iterative version of Merge Sort for an Assignment. I got the Merge sort method from a website, and I worked on the method that is supposed to merge the arrays. However I keep getting an IndexOutOfBounds Exception.
I have been working on this for multiple hours and I cannot find the error. Can someone help me find a way to solve this?
So far I have this:
public static void MergeSort(int[] array) {
int current;
int leftStart;
int arraySize = array.length - 1;
for (current = 1; current <= arraySize; current = 2 * current) {
for (leftStart = 0; leftStart <= arraySize; leftStart += 2 * current) {
int mid = leftStart + current - 1;
int right = getMin(leftStart + 2 * current - 1, arraySize);
mergeArray(array, leftStart, mid, right);
}
}
}
public static void mergeArray(int[] array, int left, int mid, int right) {
int leftArraySize = mid - left + 1;
int rightArraySize = right - mid;
int[] leftArray = new int[leftArraySize];
int[] rightArray = new int[rightArraySize];
for (int i = 0; i < leftArraySize; i++)
leftArray[i] = array[left + i];
for (int i = 0; i < rightArraySize; i++)
rightArray[i] = array[mid + 1 + i];
int leftPtr = 0;
int rightPtr = 0;
int tempPtr = leftPtr;
while (leftPtr < leftArraySize && rightPtr < rightArraySize) {
if (leftArray[leftPtr] <= rightArray[rightPtr])
array[tempPtr++] = leftArray[leftPtr++];
else
array[tempPtr++] = rightArray[rightPtr++];
}
while (leftPtr <= left)
array[tempPtr++] = leftArray[leftPtr++];
while (rightPtr < right)
array[tempPtr++] = rightArray[rightPtr++];
}
public static int getMin(int left, int right) {
if (left <= right) {
return left;
} else {
return right;
}
}
Any sort of help will be highly appreciated!
Thanks!
Merge sort algorithm is a classical Divide and Conquer algorithm.
Divide the problem into smaller sub problems
Conquer via recursive calls.
Combine solutions of sub problems into one for the original problem
The Pseudocode for Merge:
C = output[length = n]
A = 1st sorted array[n/2]
B = 2st sorted array[n/2]
i = 1
j = 1
for k = 1 to n
if A[i] < B[j]
C[k] = A[i]
i++
else B[j]<A[i]
C[k] = B[j]
j++
end (ignores end cases)
So your source code problem is this line:
array[tempPtr++] = leftArray[leftPtr++];
please change to the logic of pseudocode:
if (leftArray [leftPtr ] <= rightArray[rightPtr ])
{
array[tempPtr] = leftArray [leftPtr];
leftPtr++;
}
else
{
array[tempPtr] = rightArray[rightPtr];
rightPtr++;
}
Try this code Successfully executed:
Only Small mistake in mergeArray() method:
array[tempPtr++] = leftArray[leftPtr++];
DOn't increment in array... Replace
array[tempPtr] = leftArray [leftPtr];
leftPtr++;
Final code: Compare my code you will get it.
public static void MergeSort(int[] array) {
int current;
int leftStart;
int arraySize = array.length;
for (current = 1; current <= arraySize-1; current = 2 * current) {
for (leftStart = 0; leftStart < arraySize-1; leftStart += 2 * current) {
int mid = leftStart + current - 1;
int right = getMin(leftStart + 2 * current - 1, arraySize-1);
mergeArray(array, leftStart, mid, right);
}}}
static void printArray(int A[])
{
int i;
for (i=0; i < A.length; i++)
System.out.println(A[i]);
}
static void mergeArray(int array[], int left, int mid, int right)
{
int leftArraySize = mid - left + 1;
int rightArraySize = right - mid;
int[] leftArray = new int[leftArraySize];
int[] rightArray = new int[rightArraySize];
for (int i = 0; i < leftArraySize ; i++)
leftArray [i] = array[left + i];
for (int j = 0; j < rightArraySize; j++)
rightArray[j] = array[mid + 1+ j];
int leftPtr = 0;
int rightPtr = 0;
int tempPtr = left;
while (leftPtr < leftArraySize && rightPtr < rightArraySize)
{
if (leftArray [leftPtr ] <= rightArray[rightPtr ])
{
array[tempPtr] = leftArray [leftPtr];
leftPtr++;
}
else
{
array[tempPtr] = rightArray[rightPtr];
rightPtr++;
}
tempPtr++;
}
while (leftPtr < leftArraySize )
{
array[tempPtr++] = leftArray [leftPtr++];
leftPtr++;
tempPtr++;
}
while (rightPtr < rightArraySize)
{
array[tempPtr++] = rightArray[rightPtr++];
rightPtr++;
tempPtr++;
} }
public static int getMin(int left, int right) {
if (left <= right) {
return left;
} else {
return right;
}}
I am writing code for a bottom-up mergeSort in Java. Right now, I think there may be an indexing issue with the call to merge, but I am having trouble figuring out exactly what my problem is. Any assistance would be greatly appreciated!
public static int[] merge(int[]a, int lo1, int hi1, int lo2, int hi2) {
int[]b = new int[hi2-lo1+1];
int i = lo1;
int j = lo2;
int k = 0;
while (i <= hi1 && j <= hi2) {
if(a[i] < a[j])
b[k++] = a[i++];
else
b[k++]=a[j++];
}
while (i <= hi1)
b[k++] = a[i++];
while (j <= hi2)
b[k++] = a[j++];
for (int l = 0; l < k; l++)
a[lo1 + l] = b[l];
return a; //added
}
public static int[] betterMergeSort(int[]a, int lo, int hi){
for (int comparesize=1; comparesize < (hi-lo+1); comparesize*=2) {
for (int k=lo; k < hi; k+=2*comparesize) {
int[]holder = new int[Math.min(k+2*comparesize-1,hi)-lo+1];
holder = merge(a, k, k+comparesize-1, k+comparesize, Math.min(k+2*comparesize-1, hi));
if (holder.length == (hi-lo+1)){
for (int j=0; j<(hi-lo+1); j++)
a[lo+j] = holder[j];
}
}
}
return a;
}
Note that I need this code to return int[] for now in order to check its accuracy.
I am currently trying to transcribe a mergesort algorithm from a pseudocode level to a working implementation in java. This is my code
public int[] merge(int a[], int b[]) {
int c[] = new int[a.length + b.length];
int i = 0, j = 0;
for (int k = 0; k < c.length; k++) {
if (a[i] <= b[j]) {
c[k] = a[i++];
} else {
c[k] = b[j++];
}
}
return c;
}
The pseudocode interpretation is correct to the best of my knowledge but it keeps returning an ArrayOutofBound Exception.
Where did I get it all wrong.
This would obviously give the out of bound exception because you are not keeping track of the length of a and b arrays . Since k = a + b , a and b will always be less than k . Hence the exception.
And when you apply this check, remember to copy the remaining of the items, whether they are of a[] or b[] , to copy them to c[]. See this -
for(;i<a.length;i++)
c[k++] = a[i++];
for(;j<b.length;b++)
c[k++] = b[j++];
The merge algorithm in the way you intend to implement it is a bit more elaborated, below you'll find a correct implementation:
public int[] merge(int a[], int b[]) {
int i = 0, j = 0, k = 0;
int m = a.length, n = b.length;
int[] c = new int[m + n];
// Merge to the end of one of the source arrays
while (i < m && j < n) {
if (a[i] <= b[j]) {
c[k] = a[i];
i++;
} else {
c[k] = b[j];
j++;
}
k++;
}
// Determine which source array has elements remaining and
// append those to the result array
if (i < m) {
for (int p = i; p < m; p++) {
c[k] = a[p];
k++;
}
} else {
for (int p = j; p < n; p++) {
c[k] = b[p];
k++;
}
}
return c;
}
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.