Non-Recursive Merge Sort in Java - java

I am working on a non recursive merge sort for my CS class and it is not exactly working. I know it is being called since when I run the test program it changes the array, just not into the correct order. Can someone please help? Thanks!
private static void mergeSort(int[] a, int left, int right)
{
int midPoint = ((right + left) / 2);
int[] buffer = new int[19];
selectionSort(a, left, midPoint);
selectionSort(a, midPoint-1, right);
merge(a, buffer, 0, 9, 19);
}
private static void selectionSort(int[] a, int beginning, int end)
{
int [] temp = new int[end-1];
for(int y = 0; y < end - 1; y++)
{
temp[y] = a[y];
}
for (int i = 0; i < temp.length - 1; i++)
{
int minIndex = findMinimum(temp, i);
if (minIndex != i)
swap (temp, i, minIndex);
}
}
private static int findMinimum(int[] a, int first)
{
int minIndex = first;
for (int i = first + 1; i < a.length; i++)
{
if (a[i] < a[minIndex])
minIndex = i;
}
return minIndex;
}
private static void swap(int []a, int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
private static void merge(int[] a, int[] temp, int left, int mid, int right) {
if (mid >= a.length) return;
if (right > a.length) right = a.length;
int i = left, j = mid+1;
for (int k = left; k < right; k++) {
if (i == mid)
temp[k] = a[j++];
else if (j == right)
temp[k] = a[i++];
else if (a[j] < a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = left; k < right; k++)
a[k] = temp[k];
}

There may be other bugs, but one that sticks out is that selectionSort doesn't actually do anything to the array. You pass in an array reference as the a parameter:
private static void selectionSort(int[] a, int beginning, int end)
Since this is a reference, if selectionSort did anything to assign to any elements of a, like
a[x] = y;
it would change the element of the caller's array, like you want. But there is no statement in selectionSort that changes anything in a. The code copies elements to temp, works with temp--but then throws all the work away.

Related

MergeSort and insertionSort combination Algorithm running slower together than separately but should run faster

I have a mergesort which needs to switch into insertionSort at a specific number, which is my threshold. But my threshold can only be 1, 2 or 3 because in any other cases my mergesort becomes very slow. I cant seem to get the Code to work together.
Here is my code:
public class InsertionSort {
// I haven't found the right Threshold yet, but it should work with any number between 1-100.
public final static int M = 16;
private void Merge(int arr[], int left, int mid, int right) {
int size1 = mid - left + 1;
int size2 = right - mid;
int LeftArray[] = new int[size1];
int RightArray[] = new int[size2];
for (int i = 0; i < size1; ++i) {
LeftArray[i] = arr[left + i];
}
for (int j = 0; j < size2; ++j) {
RightArray[j] = arr[mid + 1 + j];
}
int i = 0;
int j = 0;
int k = left;
while (i < size1 && j < size2) {
if (LeftArray[i] <= RightArray[j]) {
arr[k] = LeftArray[i];
i++;
} else {
arr[k] = RightArray[j];
j++;
}
k++;
}
while (i < size1) {
arr[k] = LeftArray[i];
i++;
k++;
}
while (j < size2) {
arr[k] = RightArray[j];
j++;
k++;
}
}
public void MergeSort(int arr[], int left, int right, int M) {
if ( left < right ) {
int mid = (left + right) / 2;
MergeSort(arr, left, mid, M);
MergeSort(arr, (mid+1), right, M);
Merge(arr, left, mid, right);
} else if ((right - left + 1) <= M) {
insertion_sort(arr, left, right);
}}
static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
static int[] readIntfile(String filename) throws Exception {
// Read file into a byte array, and then combine every group of four bytes to an
// int. (Not
// the standard way, but it works!)
byte[] bytes = Files.readAllBytes(Paths.get(filename));
int[] ints = new int[bytes.length / 4];
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < 4; j++) {
ints[i] += (bytes[i * 4 + j] & 255) << (3 - j) * 8;
}
}
return ints;
}
public static void insertion_sort(int a[], int left, int right) {
int j;
for (int i = left; i <= right; i++) {
int tmp = a[i];
for (j = i; j > 0 && tmp < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
public static void main(String args[]) throws Exception {
// I have texfile named this with 1000000 numbers
int arr[] = readIntfile("smallints");
// you can also try with this array for example
// int arr[] = {3, 6, 4, 8, 500, 1, 5, 10, 7, 9, 0, 2, 100, 300, 1000, 20, 13, 17, 55, 93};
InsertionSort insert = new InsertionSort();
long before = System.currentTimeMillis();
insert.MergeSort(arr, 0, arr.length-1, M);
long after = System.currentTimeMillis();
printArray(arr);
System.out.println("\n" + "Done " + ((after - before) / 1000.0 + " sek"));
}
}
public void MergeSort(int arr[], int left, int right, int M) {
if ( left < right ) {
int mid = (left + right) / 2;
MergeSort(arr, left, mid, M);
MergeSort(arr, (mid+1), right, M);
Merge(arr, left, mid, right);
} else if ((right - left + 1) <= M) {
insertion_sort(arr, left, right);
}}
You have a serious problem here. You have a class global variable, M, which is your insertion sort threshold, and you have a parameter, M, which is the length of the subarray you want to sort. The parameter is going to shadow the class global. Basically, your public final static int M = 16; is never seen inside the MergeSort method.
Also, if left is not less than right, then there's nothing to sort. I think you want something like this:
public final static int insertionThreshold = 16;
public void MergeSort(int arr[], int left, int right, int M) {
if ( left < right ) {
if (left - right <= insertionThreshold) {
insertion_sort(arr, left, right);
else {
int mid = (left + right) / 2;
MergeSort(arr, left, mid, M);
MergeSort(arr, (mid+1), right, M);
Merge(arr, left, mid, right);
}
}
}

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.

Iterative Java merge sort

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

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.

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