I am new to Java and have tried to implement mergesort in Java. However, even after running the program several times, instead of the desired sorted output, I am getting the same user given input as the output. I would be thankful if someone could help me understand this unexpected behaviour.
import java.io.*;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) throws IOException {
BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
int arraySize = Integer.parseInt(R.readLine());
int[] inputArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
inputArray[i] = Integer.parseInt(R.readLine());
}
mergeSort(inputArray);
for (int j = 0; j < inputArray.length; j++) {
System.out.println(inputArray[j]);
}
}
static void mergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] leftArray = Arrays.copyOfRange(A, 0, q);
int[] rightArray = Arrays.copyOfRange(A, q + 1, A.length);
mergeSort(leftArray);
mergeSort(rightArray);
A = merge(leftArray, rightArray);
}
}
static int[] merge(int[] l, int[] r) {
int totElem = l.length + r.length;
int[] a = new int[totElem];
int i, li, ri;
i = li = ri = 0;
while (i < totElem) {
if ((li < l.length) && (ri < r.length)) {
if (l[li] < r[ri]) {
a[i] = l[li];
i++;
li++;
} else {
a[i] = r[ri];
i++;
ri++;
}
} else {
if (li >= l.length) {
while (ri < r.length) {
a[i] = r[ri];
i++;
ri++;
}
}
if (ri >= r.length) {
while (li < l.length) {
a[i] = l[li];
li++;
i++;
}
}
}
}
return a;
}
}
Here is a corrected version of your code:
import java.io.*;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) throws IOException{
BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
int arraySize = Integer.parseInt(R.readLine());
int[] inputArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
inputArray[i] = Integer.parseInt(R.readLine());
}
mergeSort(inputArray);
for (int j = 0; j < inputArray.length; j++) {
System.out.println(inputArray[j]);
}
}
static void mergeSort(int[] A) {
if (A.length > 1) {
int q = A.length/2;
//changed range of leftArray from 0-to-q to 0-to-(q-1)
int[] leftArray = Arrays.copyOfRange(A, 0, q-1);
//changed range of rightArray from q-to-A.length to q-to-(A.length-1)
int[] rightArray = Arrays.copyOfRange(A,q,A.length-1);
mergeSort(leftArray);
mergeSort(rightArray);
merge(A,leftArray,rightArray);
}
}
static void merge(int[] a, int[] l, int[] r) {
int totElem = l.length + r.length;
//int[] a = new int[totElem];
int i,li,ri;
i = li = ri = 0;
while ( i < totElem) {
if ((li < l.length) && (ri<r.length)) {
if (l[li] < r[ri]) {
a[i] = l[li];
i++;
li++;
}
else {
a[i] = r[ri];
i++;
ri++;
}
}
else {
if (li >= l.length) {
while (ri < r.length) {
a[i] = r[ri];
i++;
ri++;
}
}
if (ri >= r.length) {
while (li < l.length) {
a[i] = l[li];
li++;
i++;
}
}
}
}
//return a;
}
}
When you rebind A in mergeSort():
A = merge(leftArray,rightArray);
this has no effect in inputArray in main().
You need to return the sorted array from mergeSort() similarly to how you return it from merge().
static int[] mergeSort(int[] A) {
...
return A;
}
and in main():
int[] mergedArray = mergeSort(inputArray);
for (int j = 0; j < mergedArray.length; j++) {
System.out.println(mergedArray[j]);
}
The problem is that java is pass by value and not pass by reference... When you are assigning to array A in the merge method you are changing a copy of the reference to A and not the reference to A itself. Therefore you need to pass A into your merge method and make a structural change to A.
The problem lies here:
A = merge(leftArray,rightArray);
Now your merge array does this:
static int[] merge(int[] l, int[] r) {
int[] a = new int[totElem];
// bunch of code
return a;
}
When you started, A was a reference to inputArray. But then you reassigned it to be whatever came out of merge. Unfortunately, that doesn't touch what inputArray is in the main method. That basically says "Oh look at all the work you did... throw it away!"
You could change that with something like
static int[] mergeSort(int[] A) {
// A = merge... // not this
return merge... // use this
}
Then in your main method, you can do
int[] merged = mergeSort(inputArray);
for(int i : merged) System.out.println(i);
public class MergeSort{
public static void sort(int[] in){
if(in.length <2) return; //do not need to sort
int mid = in.length/2;
int left[] = new int[mid];
int right[] = new int[in.length-mid];
for(int i=0; i<mid; i++){ //copy left
left[i] = in[i];
}
for(int i=0; i<in.length-mid; i++){ //copy right
right[i] = in[mid+i];
}
sort(left);
sort(right);
merge(left, right, in);
}
private static void merge(int[] a, int[] b, int[] all){
int i=0, j=0, k=0;
while(i<a.length && j<b.length){ //merge back
if(a[i] < b[j]){
all[k] = a[i];
i++;
}else{
all[k] = b[j];
j++;
}
k++;
}
while(i<a.length){ //left remaining
all[k++] = a[i++];
}
while(j<b.length){ //right remaining
all[k++] = b[j++];
}
}
public static void main(String[] args){
int[] a = {2,3,6,4,9,22,12,1};
sort(a);
for(int j=0; j<a.length; j++){
System.out.print(a[j] + " ");
}
}
}
public void sort(int[] randomNumbersArrray)
{
copy = randomNumbersArrray.clone();
mergeSort(0 , copy.length - 1);
}
private void mergeSort(int low, int high)
{
if(low < high)
{
int mid = ((low + high) / 2);
mergeSort(low, mid); //left side
mergeSort(mid + 1, high); // right side
merge(low, mid, high); //combine them
}
}
private void merge(int low, int mid, int high)
{
int temp[] = new int[high - low + 1];
int left = low;
int right = mid + 1;
int index = 0;
// compare each item for equality
while(left <= mid && right <= high)
{
if(copy[left] < copy[right])
{
temp[index] = copy[left];
left++;
}else
{
temp[index] = copy[right];
right++;
}
index++;
}
// if there is any remaining loop through them
while(left <= mid || right <= high)
{
if( left <= mid)
{
temp[index] = copy[left];
left++;
index++;
}else if(right <= high)
{
temp[index] = copy[right];
right++;
index++;
}
}
// copy back to array
for(int i = 0; i < temp.length; i++)
{
copy[low + i] = temp[i];
}
}
package Sorting;
public class MergeSort {
private int[] original;
private int len;
public MergeSort(int length){
len = length;
original = new int[len];
original[0]=10;
original[1]=9;
original[2]=8;
original[3]=7;
original[4]=6;
original[5]=5;
original[6]=4;
original[7]=3;
original[8]=2;
original[9]=1;
int[] aux = new int[len];
for(int i=0;i<len;++i){
aux[i]=original[i];
}
Sort(aux,0,len);
}
public void Sort(int[] aux,int start, int end){
int mid = start + (end-start)/2;
if(start < end){
Sort(aux, start, mid-1);
Sort(aux, mid, end);
Merge(aux, start, mid, end);
}
}
public void Merge(int[] aux, int start, int mid, int end){// while array passing be careful of shallow and deep copying
for(int i=start; i<=end; ++i)
auxilary[i] = original[i];
int i = start;
int k = start;
int j = mid+1;
while(i < mid && j <end){
if(aux[i] < aux[j]){
original[k++] = aux[i++];
}
else{
original[k++] = aux[j++];
}
}
if(i == mid){
while(j < end){
original[k++] = aux[j++];
}
}
if(j == end){
while(i < mid){
original[k++] = aux[i++];
}
}
}
public void disp(){
for(int i=0;i<len;++i)
System.out.print(original[i]+" ");
}
public static void main(String[] args) {
MergeSort ms = new MergeSort(10);
ms.disp();
}
}
The above codes are a little confused
Never use variables with names: "k", "j", "m",... this makes the code very confusing
Follows the code in an easier way...
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
Integer[] itens = {2,6,4,9,1,3,8,7,0};
Integer[] tmp = new Integer[itens.length];
int left = 0;
int right = itens.length - 1;
mergeSort(itens, tmp, left, right);
System.out.println(Arrays.toString(itens));
}
private static void mergeSort(Integer[] itens, Integer[] tmpArray, int left, int right) {
if(itens == null || itens.length == 0 || left >= right){
return;
}
int midle = (left + right) / 2;
mergeSort(itens, tmpArray, left, midle);
mergeSort(itens, tmpArray, midle + 1, right);
merge(itens, tmpArray, left, midle + 1, right);
}
private static void merge(Integer[] itens, Integer[] tmpArray, int left, int right, int rightEnd) {
int leftEnd = right - 1;
int tmpIndex = left;
while (left <= leftEnd && right <= rightEnd){
if (itens[left] < itens[right] ){
tmpArray[tmpIndex++] = itens[left++];
} else {
tmpArray[tmpIndex++] = itens[right++];
}
}
while (left <= leftEnd) { // Copy rest of LEFT half
tmpArray[tmpIndex++] = itens[left++];
}
while (right <= rightEnd) { // Copy rest of RIGHT half
tmpArray[tmpIndex++] = itens[right++];
}
while(rightEnd >= 0){ // Copy TEMP back
itens[rightEnd] = tmpArray[rightEnd--];
}
}
}
Might as well add my take on this:
Takes two int arrays and merges them.
Where 'result' is an array of size a.length + b.length
public static void merge( int[] a, int[] b, int[] result )
{
int i = 0, j = 0;
while ( true )
{
if ( i == a.length )
{
if ( j == b.length )
return;
result[ i + j ] = b[ j ];
j++;
}
else if ( j == b.length )
{
result[ i + j ] = a[ i ];
i++;
}
else if ( a[ i ] < b[ j ] )
{
result[ i + j ] = a[ i ];
i++;
}
else
{
result[ i + j ] = b[ j ];
j++;
}
}
}
public class MyMergeSort {
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String a[]){
int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
very simple and easy to understand
static void sort(char[] data) {
int length = data.length;
if (length < 2)
return;
int mid = length / 2;
char[] left = new char[mid];
char[] right = new char[length - mid];
for(int i=0;i<mid;i++) {
left[i]=data[i];
}
for(int i=0,j=mid;j<length;i++,j++) {
right[i]=data[j];
}
sort(left);
sort(right);
merge(left, right, data);
}
static void merge(char[] left, char[] right, char[] og) {
int i = 0, j = 0, k = 0;
while(i < left.length && j < right.length) {
if (left[i] < right[j]) {
og[k++] = left[i++];
} else {
og[k++] = right[j++];
}
}
while (i < left.length) {
og[k++] = left[i++];
}
while (j < right.length) {
og[k++] = right[j++];
}
}
I have a parallel version of Merge Sort. I am benefiting from the RecursiveAction and ForkJoinPool. Note that the number of workers can be set as a constant. However, I am setting it as the number of available processors on the machine.
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ParallelMergeSorter {
private int[] array;
public ParallelMergeSorter(int[] array) {
this.array = array;
}
public int[] sort() {
int numWorkers = Runtime.getRuntime().availableProcessors(); // Get number of available processors
ForkJoinPool pool = new ForkJoinPool(numWorkers);
pool.invoke(new ParallelWorker(0, array.length - 1));
return array;
}
private class ParallelWorker extends RecursiveAction {
private int left, right;
public ParallelWorker(int left, int right) {
this.left = left;
this.right = right;
}
protected void compute() {
if (left < right) {
int mid = (left + right) / 2;
ParallelWorker leftWorker = new ParallelWorker(left, mid);
ParallelWorker rightWorker = new ParallelWorker(mid + 1, right);
invokeAll(leftWorker, rightWorker);
merge(left, mid, right);
}
}
private void merge(int left, int mid, int right) {
int[] leftTempArray = Arrays.copyOfRange(array, left, mid + 1);
int[] rightTempArray = Arrays.copyOfRange(array, mid + 1, right + 1);
int leftTempIndex = 0, rightTempIndex = 0, mergeIndex = left;
while (leftTempIndex < mid - left + 1 || rightTempIndex < right - mid) {
if (leftTempIndex < mid - left + 1 && rightTempIndex < right - mid) {
if (leftTempArray[leftTempIndex] <= rightTempArray[rightTempIndex]) {
array[mergeIndex] = leftTempArray[leftTempIndex];
leftTempIndex++;
} else {
array[mergeIndex] = rightTempArray[rightTempIndex];
rightTempIndex++;
}
} else if (leftTempIndex < mid - left + 1) {
array[mergeIndex] = leftTempArray[leftTempIndex];
leftTempIndex++;
} else if (rightTempIndex < right - mid) {
array[mergeIndex] = rightTempArray[rightTempIndex];
rightTempIndex++;
}
mergeIndex++;
}
}
}
}
public class MergeTwoSortedArray {
public void approach_2(int[] arr1, int[] arr2) {
List<Integer> result = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).boxed().sorted()
.collect(Collectors.toList());
System.out.println(result);
}
public void approach_3(Integer[] arr1, Integer[] arr2) {
List<Integer> al1 = Arrays.asList(arr1);
List<Integer> al2 = Arrays.asList(arr2);
List<Integer> result = new ArrayList<>();
int i = 0, j = 0;
while (i < al1.size() && j < al2.size()) {
if (al1.get(i) < al2.get(j)) {
result.add(al1.get(i));
i++;
} else {
result.add(al2.get(j));
j++;
}
}
while (i < al1.size()) {
result.add(al1.get(i));
i++;
}
while (j < al2.size()) {
result.add(al2.get(j));
j++;
}
System.out.println(result);
}
public static void main(String[] args) {
MergeTwoSortedArray obj = new MergeTwoSortedArray();
int[] arr1 = { 3, 6, 76, 85, 91 };
int[] arr2 = { 1, 6, 78, 89, 95, 112 };
obj.approach_2(arr1, arr2);
Integer[] arr3 = { 3, 6, 76, 85, 91 };
Integer[] arr4 = { 1, 6, 78, 89, 95, 112 };
obj.approach_3(arr3, arr4);
}
}
Related
Trying to get it from big to little I'm trying to use the Sort & Search Merge Sort:
import java.util.*;
class MergeSorter {
public static void sort(int[] a) {
if (a.length <= 1) { return; }
int[] first = new int[a.length / 2];
int[] second = new int[a.length - first.length];
for (int i = 0; i < first.length; i++) {
first[i] = a[i];
}
for (int i = 0; i < second.length; i++) {
second[i] = a[first.length + i];
}
sort(first);
sort(second);
merge(first, second, a);
}
private static void merge(int[] first, int[] second, int[] a) {
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
a[j] = first[iFirst];
iFirst++;
} else {
a[j] = second[iSecond];
iSecond++;
}
j++;
}
while (iFirst < first.length) {
a[j] = first[iFirst];
iFirst++; j++;
}
while (iSecond < second.length) {
a[j] = second[iSecond];
iSecond++; j++;
}
}
}
public class MergeSortDemo888888 {
public static void main(String[] args) {
int [] myAry = { 3, 2, 6, 7 };
System.out.println("myAry is " + Arrays.toString(myAry));
MergeSorter.sort(myAry);
System.out.println("myAry is sorted descendingly using selection sort: "+Arrays.toString(myAry));
}
}
In the first if in the merge function just change this (first[iFirst] < second[iSecond]) into this (first[iFirst] > second[iSecond]).
I've been trying hard to find where the problem is. But everytime I run this program, it shows :
Exception in thread "main" java.lang.NullPointerException
at MergeSortTest.mergeSort(MergeSortTest.java:8)
Can someone please help me how to fix this?
public class MergeSortTest
{
private static int[] arr;
public static void mergeSort(int[] array)
{
int start = 0;
int end = arr.length - 1;
mergeSort(start, end);
array = arr;
}
public static void mergeSort(int start, int end)
{
if (start == end) {
return;
}
int center = (start + end) / 2;
mergeSort(start, center);
mergeSort(center + 1, end);
merge(start, center + 1, end);
}
public static void merge(int left, int right, int rightEnd)
{
int k = left;
int leftEnd = right-1;
int num = rightEnd - left + 1;
int front[] = new int[leftEnd - left + 1];
int back[] = new int[rightEnd - right + 1];
for (int i = left; i < front.length; i++)
{
front[i] = arr[i];
}
for (int i = right; i < back.length; i++)
{
back[i] = arr[i];
}
int[] temp = new int[num];
while (true)
{
if (front[left] <= back[right])
{
if (left < leftEnd)
{
temp[k] = front[left];
k++;
left++;
}
if (left == leftEnd)
{
temp[k] = front[left];
for (right = right; right < rightEnd + 1; right++)
{
k++;
temp[k] = back[right];
}
break;
}
}
else
{
if (right < rightEnd)
{
temp[k] = back[right];
k++;
right++;
}
if (right == rightEnd)
{
temp[k] = back[left];
for(left = left; left < leftEnd+1; left++)
{
k++;
temp[k] = front[left];
}
break;
}
}
}
}
public static void main(String []args)
{
int[] array = new int[10];
initializeRandom(array);
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
mergeSort(array);
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
public static void initializeRandom(int[] array)
{
for (int i = 0; i < array.length; i++)
{
array[i] = (int)(Math.random() * 10 + 1);
}
}
}
You aren't using the array you're passing as a parameter, but using uninitialized one:
private static int[] arr;
// ...
int end = arr.length - 1;
In your main method:
mergeSort(array);
You need to either pass the arr down to merge or rewrite your logic.
I have taken a given int array and broken it into multiple sub arrays and put it into an ArrayList.
1) I need to spawn one thread per index of a. (this is not working and causing threads to used the same data)
2) I need to send each thread to be sorted via the quicksort class.(as it stands this works)
3) I also need to merge all the threads sorted arrays into one sorted array.(not sure how to do this either)
public void run(ArrayList<int[]> a) {
Quicksort x = new Quicksort();
for (int i = 0; i < a.size(); i++) {
store = a.get(i);
System.out.println(store);
new Thread() {
public void run() {
x.sort(store);
System.out.println(Arrays.toString(store));
}
}.start();
}
}
public class Quicksort {
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
i++;
j--;
}
}
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
how I populate a
public class ArrayLists {
private ArrayList<int[]> List = new ArrayList<>();
public ArrayLists(int[] a, int size) {
int[] temp = new int[size];
int count = 0;
while (count + size <= a.length) {
temp = Arrays.copyOfRange(a, count, count + size);
List.add(temp);
count = count + size;
}
int[] temp2 = new int[a.length - count];
if (count != a.length && count < a.length) {
temp2 = Arrays.copyOfRange(a, count, a.length);
List.add(temp2);
}
run(List);
}
the issue was how I used the store variable. I needed a final int[] instead of a static int[] global variable.
The Merging function:
static int[] merge(int v[], int start, int middle, int end){
int i = start, temp, j = middle, k = 0;
int a[] = new int[end];
while(j < end && i < middle){
if(v[i] > v[j]){
a[k++] = v[j++];
}
else{
a[k++] = v[i++];
}
}
for(temp = i; temp < middle; temp++){
a[k++] = v[temp];
}
for(temp = j; temp < end; temp++){
a[k++] = v[temp];
}
for(i = 0; i < end; i++)
v[i] = a[i];
return v;
}
The Splitting Function:
static int[] split(int v[], int start, int end){
int array[] = new int[end-start+1];
for(int i = start, j = 0; i <= end; i++, j++){
array[j] = v[i];
}
return array;
}
The MergeSort Function:
static int[] mergesort(int v[], int start, int end) {
int middle = v.length/2, left, right;
if(end-start <= 1){
return v;
}
mergesort(split(v, start, middle), start, middle);
mergesort(split(v, middle+1, end-1), middle+1, end-1);
merge(v, start, middle, end);
return v;
}
The Main function:
public static void main(String[] args){
int v[] = {6,1,8,2,9,3};
int end = 6, i;
v = mergesort(v, 0, end);
for(i = 0; i < end; i++){
System.out.print(v[i]+" ");
}
System.out.println();
}
The output given is 2 6 1 8 9 3 and should be 1 2 3 6 8 9
I'm pretty sure it's here:
mergesort(split(v, start, middle), start, middle);
mergesort(split(v, middle+1, end-1), middle+1, end-1);
merge(v, start, middle, end);
these functions return an array but what can i assign it to ?
Here is my solution, which is using lists instead of arrays.
public <E extends Comparable<E>> List<E> mergeSort(List<E> unsortedList) {
if (unsortedList == null || unsortedList.size() < 2) {
return unsortedList;
} else {
List<E> left = new LinkedList<E>();
List<E> right = new LinkedList<E>();
int pivot = (1 + unsortedList.size()) / 2;
while (!unsortedList.isEmpty()) {
if (pivot > 0) {
left.add(unsortedList.remove(0));
pivot--;
} else {
right.add(unsortedList.remove(0));
}
}
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
}
private <E extends Comparable<E>> List<E> merge(List<E> left, List<E> right) {
List<E> sortedResult = new ArrayList<E>(left.size() + right.size());
while (!left.isEmpty() && !right.isEmpty()) {
E leftElem, rightElem;
leftElem = left.get(0);
rightElem = right.get(0);
if (leftElem.compareTo(rightElem) < 0) {
sortedResult.add(leftElem);
left.remove(0);
} else {
sortedResult.add(rightElem);
right.remove(0);
}
}
sortedResult.addAll(left);
sortedResult.addAll(right);
return sortedResult;
}
INPUT:
[6, 1, 3, 5, 5, 1, 9, 8, 7, 8]
OUTPUT:
[1, 1, 3, 5, 5, 6, 7, 8, 8, 9]
You are complicating a little bit your code. Here is an alternative implementation. Let me know if it works:
class MergeSort2{
public static void main(String[] args){
int[] arrayToMerge = new int[]{45,66,7,8,444,3,5,66,7,1,9,3,55,6,7};
mergeSort(arrayToMerge, 0 , arrayToMerge.length-1);
for(int i=0; i < arrayToMerge.length; i++){
System.out.println(" -> " + arrayToMerge[i]);
}
}
public static void mergeSort(int[] arr, int start, int end){
if(start < end){
int mid = (start + end) /2;
mergeSort(arr,start, mid);
mergeSort(arr, mid + 1, end);
mergeArray(arr, start, mid, end);
}
}
public static void mergeArray(int[] arr, int start, int mid, int end){
int[] temp = new int[end - start + 1];
int i= start, j = mid + 1 , k = 0;
while(i <= mid && j <= end){
if(arr[i] < arr[j]){
temp[k] = arr[i];
k++;
i++;
}
else
{
temp[k] = arr[j];
k++;
j++;
}
}
while(i <= mid){
temp[k] = arr[i];
k++;
i++;
}
while (j <= end){
temp[k] = arr[j];
k++;
j++;
}
i= start;
k=0;
while (k < temp.length && i <= end){
arr[i] = temp[k];
i++;
k++;
}
}
}
I am trying to run my code so it prints cyclic permutations, though I can only get it to do the first one at the moment. It runs correctly up to the point which I have marked but I can't see what is going wrong. I think it has no break in the while loop, but I'm not sure. Really could do with some help here.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPemutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPemutation(int p[])// (b)
{
System.out
.println("The permutation is represented by the cyclic notation:");
int[] B = new int[p.length];
int m = 0;
while (m < p.length)// this is the point at which my code screws up
{
if (!check(B, m)) {
B = parenthesis(p, m);
printParenthesis(B);
m++;
} else
m++;
}// if not there are then repeat
}
static int[] parenthesis(int p[], int i) {
int[] B = new int[p.length];
for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) {
B[j] = a;
}
return B;
}
static void printParenthesis(int B[]) {
System.out.print("( ");
for (int i = 0; i < B.length && B[i] != 0; i++)
System.out.print(B[i] + " ");
System.out.print(")");
}
static boolean check(int B[], int m) {
int i = 0;
boolean a = false;
while (i < B.length || !a) {
if ((ispresent(m, B, i))){
a = true;
break;
}
else
i++;
}
return a;
}
static boolean ispresent(int m, int B[], int i) {
return m == B[i] && m < B.length;
}
}
Among others you should check p[m] in check(B, p[m]) instead of m:
in static void printPemutation(int p[]):
while (m < p.length){
if (!check(B, p[m])) {
B = parenthesis(p, m);
printParenthesis(B);
}
m++;
}
then
static boolean check(int B[], int m) {
int i = 0;
while (i < B.length) {
if (m == B[i]) {
return true;
}
i++;
}
return false;
}
this does somehow more what you want, but not always i fear...