MergeSort gives StackOverflow error - algorithm

this is the code for the mergeSort,this gives an stackoverflow error in line 53 and 54(mergeSort(l,m); and mergeSort(m,h);)
Any help will be regarded so valuable,please help me out,i am clueless,Thank you.
package codejam;
public class vector {
static int[] a;
static int[] b;
public static void main(String[] args) {
int[] a1 = {12,33,2,1};
int[] b1 = {12,333,11,1};
mergeSort(0,a1.length);
a1=b1;
mergeSort(0,b1.length);
for (int i = 0; i < a1.length; i++) {
System.out.println(a[i]);
}
}
public static void merge(int l,int m,int h) {
int n1=m-l+1;
int n2 = h-m+1;
int[] left = new int[n1];
int[] right = new int[n2];
int k=l;
for (int i = 0; i < n1 ; i++) {
left[i] = a[k];
k++;
}
for (int i = 0; i < n2; i++) {
right[i] = a[k];
k++;
}
left[n1] = 100000000;
right[n1] = 10000000;
int i=0,j=0;
for ( k =l ; k < h; k++) {
if(left[i]>=right[j])
{
a[k] = right[j];
j++;
}
else
{
a[k] = left[i];
i++;
}
}
}
public static void mergeSort(int l,int h) {
int m =(l+h)/2;
if(l<h)
{
mergeSort(l,m);
mergeSort(m,h);
merge(l,m,h);;
}
}
}

Following is the recursive iterations table of the mergeSort function with argument l=0 and h=4
when the value of l is 0 and value of h is 1 , expression calculate m value which turn out to be 0 but we are checking condition with h which is still 1 so 0<1 become true , recursive calls of this mergeSort function forms a pattern , this pattern doesn't let the function to terminate , stack runs out of memory , cause stackoverflow error.

import java.lang.*;
import java.util.Random;
public class MergeSort {
public static int[] merge_sort(int[] arr, int low, int high ) {
if (low < high) {
int middle = low + (high-low)/2;
merge_sort(arr,low, middle);
merge_sort(arr,middle+1, high);
arr = merge (arr,low,middle, high);
}
return arr;
}
public static int[] merge(int[] arr, int low, int middle, int high) {
int[] helper = new int[arr.length];
for (int i = 0; i <=high; i++){
helper[i] = arr[i];
}
int i = low;
int j = middle+1;
int k = low;
while ( i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
arr[k++] = helper[i++];
} else {
arr[k++] = helper[j++];
}
}
while ( i <= middle){
arr[k++] = helper[i++];
}
while ( j <= high){
arr[k++] = helper[j++];
}
return arr;
}
public static void printArray(int[] B) {
for (int i = 0; i < B.length ; i++) {
System.out.print(B[i] + " ");
}
System.out.println("");
}
public static int[] populateA(int[] B) {
for (int i = 0; i < B.length; i++) {
Random rand = new Random();
B[i] = rand.nextInt(20);
}
return B;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int A[] = new int[10];
A = populateA(A);
System.out.println("Before sorting");
printArray(A);
A = merge_sort(A,0, A.length -1);
System.out.println("Sorted Array");
printArray(A);
}
}

Related

What is correct solution for this (Benny and Segments) question on Hackerearth?

How do i correctly solve this question Benny and Segments. The solution given for this question is not correct . According to editorial for this question, following is a correct solution.
import java.io.*; import java.util.*;
class Pair{
int a; int b;
public Pair(int a , int b){ this.a = a; this.b = b;}
}
class TestClass {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static void rl() throws Exception{st = new StringTokenizer(br.readLine());}
static int pInt() {return Integer.parseInt(st.nextToken());}
public static void main(String args[] ) throws Exception {
rl();
int T = pInt();
while(T-- > 0){
rl();
int N = pInt();
int L = pInt();
Pair[] p = new Pair[N];
for(int i = 0; i < N; i++){
rl();
int l = pInt();
int r = pInt();
p[i] = new Pair(l, r);
}
Arrays.sort(p, new Comparator<Pair>(){
#Override
public int compare(Pair o1, Pair o2)
{
return o1.a - o2.a;
}
});
boolean possible = false;
for(int i = 0; i < N; i++){
int start = p[i].a;
int curr_max = p[i].b;
int req_max = p[i].a + L;
for(int j = 0; j < N; j++){
if(p[i].a <= p[j].a && p[j].b <= req_max){
curr_max = Math.max(curr_max, p[j].b);
}
}
if(curr_max == req_max ){
System.out.println("Yes");
possible = true;
break;
}
}
if(!possible)
System.out.println("No");
}
}
}
But this will certainly fail for the following testcase. It will give "Yes" when it should have given "No", Because there is no continuous path of length 3.
1
3 3
1 2
3 4
4 5
As suggested by kcsquared. I modified my code.
It runs correctly. I think Question setters had set weak test case for this question.
As your test-case demonstrates, the error is that when adding new segments to extend the current segment, there's no test to check whether the new segment can reach the current segment or would leave a gap. To do so, compare the new segment's left end to your current segment's right end:
for(int j = i + 1; j < N; j++){
if(p[j].a <= curr_max && p[j].b <= req_max){
curr_max = Math.max(curr_max, p[j].b);
}
}

I was trying to build a merge sort but ending up with an error

The method mergeSort(int[]) is undefined for the type merge. This is the error that I am facing. Can anyone please point out my fault? Might be I'm making a syntax error, please point out the mistake im making.
public class merge {
public static mergeSort(int[] a) {
int n = a.length;
if (n < 2) {
return(a[]);
}
int mid = n / 2;
int left[] = new int[mid];
int left[] = new int[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = a[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = a[i];
}
mergeSort(left[]);
mergeSort(right[]);
mmerge(left[], right[], A);
}
public static void mmerge(int[] l, int[] r, int[] array) {
int len1 = l.length();
int len2 = r.length();
int i = 0;
int j = 0;
int k = 0;
while (i < len1 && j < len2) {
if (l[i] <= r[j]) {
array[k]=l[i];
k++;
i++;
} else {
array[k] = r[j];
k++;
j++;
}
}
while (i < len1) {
array[k] = l[i];
k++;
i++;
}
while (j < len2) {
array[k] = r[j];
k++;
j++;
}
}
public static void main(String args[]) {
int[] arr = { 4, 6, 2, 9, 1, 7, 3 };
mergeSort(arr);
for (int p = 0; p < arr.length; p++) {
System.out.print(arr[p]+" ");
}
}
}
Try this
public class merge {
public static void mergeSort(int[] a) {
int n=a.length;
if(n<2) {
return;
}
int mid=n/2;
int left[]=new int[mid];
int right[]=new int[n-mid];
for (int i=0;i<mid;i++) {
left[i]=a[i];
}
for (int i=mid;i<n;i++) {
right[i-mid]=a[i];
}
mergeSort(left);
mergeSort(right);
mmerge(left,right,a);
}
public static void mmerge(int[] l,int[] r,int[] array) {
int len1=l.length;
int len2=r.length;
int i=0;
int j=0;
int k=0;
while(i<len1 && j<len2) {
if(l[i]<=r[j]) {
array[k]=l[i];
k++;
i++;
}else {
array[k]=r[j];
k++;
j++;
}
}
while(i<len1) {
array[k]=l[i];
k++;
i++;
}
while(j<len2) {
array[k]=r[j];
k++;
j++;
}
}
public static void main(String args[]) {
int[] arr={4,6,2,9,1,7,3};
mergeSort(arr);
for(int p=0;p<arr.length;p++) {
System.out.print(arr[p]+" ");
}
}
}

Sorting algorithm is skipping the last element in my array

I have a simple algorithm to order numbers in an array, all of the elements become ordered except for the last one. I have tried changing the bounds of my loops to fix this, but it just creates an infinite loop instead.
while (pointer < arrayLength){
int min = findMinFrom(pointer);
for (int i = pointer; i < arrayLength; i ++){
if (A[i] == min){
swap(i, pointer);
pointer ++;
}
compNewS ++;
}
}
You see what's the problem? Your pointer will be updated only if A[i] == min if not then it will keep looping. Put your pointer++ out of that condition.
This can be done with only two loops but here is an adjusted version of your code:
public class Numbers {
private static int [] A ;
public static void main(String [] args) {
int [] array = {3,2,1,4,5,6,7,8,9,7};
A = array;
newSort(array, array.length);
for(int i = 0; i < A.length;i++)
System.out.println(A[i]);
}
public static void newSort(int[] array, int arrayLength){
int pointer = 0;
int p = 0;
while(p < array.length) {
int min = findMinFrom(p,array);
int temp = array[p];
array[p] = min;
array[min] = temp;
p++;
}
}
public static int findMinFrom(int p, int[] array){
int min = p;
for (int i = p; i < array.length; i ++){
if (A[i] < array[p]){
min =i;
}
}
return min;
}
}

Two ways of doing Counting Sort

Here are my two implementations of Counting Sort
In this implementation which is a very simple one, all I do is count the number of occurrences of the element, and insert as many times as the occurrences in the output array.
Implementation 1
public class Simple
{
static int[] a = {5,6,6,4,4,4,8,8,8,9,4,4,3,3,4};
public static void main(String[] args)
{
fun(a);
print(a);
}
static void fun(int[] a)
{
int max = findMax(a);
int[] temp = new int[max+1];
for(int i = 0;i<a.length;i++)
{
temp[a[i]]++;
}
print(temp);
//print(temp);
int k = 0;
for(int i = 0;i<temp.length;i++)
{
for(int j = 0;j<temp[i];j++)
a[k++] = i;
}
print(a);
}
static int findMax(int[] a)
{
int max = a[0];
for(int i= 1;i<a.length;i++)
{
if(a[i] > max)
max = a[i];
}
return max;
}
static void print(int[] a)
{
for(int i = 0;i<a.length;i++)
System.out.print(a[i] + " ");
System.out.println("");
}
}
Implementation 2
In this implementation which I saw on a lot of places online, you create an array saying how many elements there exists less than or equal to, that element, and then insert the element at that position. Once you insert, you reduce the count of the number of elements that are less than or equal to that element, since you have included that element. By the element, this array turns to all zeros. As you can see this implementation is fairly complex compared to the previous one, and am not sure why this is widely popular online.
public class NotVerySimple {
public static void main(String[] args) {
static int[] a = {5,6,6,4,4,4,8,8,8,9,4,4,3,3,4};
sort(a);
}
static void sort(int[] a)
{
int min = smallest(a);
int max = largest(a);
int[] A = new int[max - min + 1];
for(int i = 0;i<a.length;i++)
{
A[a[i] - min]++;
}
for(int i = 1;i<A.length;i++)
A[i] = A[i-1] + A[i];
int[] B = new int[a.length];
for(int i = 0;i<a.length;i++)
{
B[ A[a[i] - min] - 1 ] = a[i];
A[a[i] - min]--;
}
print(B);
}
static int smallest(int[] a)
{
int ret = a[0];
for(int i = 1;i<a.length;i++)
{
if(a[i] < ret)
ret = a[i];
}
return ret;
}
static int largest(int[] a)
{
int ret = a[0];
for(int i = 1;i<a.length;i++)
{
if(a[i] > ret)
ret = a[i];
}
return ret;
}
static void print(int[] a)
{
for(int x : a)
System.out.print(x+ " ");
}
}
Are there any advantages of the second complex implementation as compared to the first simple one, which makes it so popular?

print shapes in java

I want to print this shape big X from collection of small x using recursion
this is my code
private static void shape(PrintWriter output, int times, int k, int times2) {
if(times < 0){
return;
} else{
for (int i =0; i<times; i++){
if (i==times)
output.print("X");
else if(i==k)
output.print("X");
else
output.print(" ");
}
output.println();
shape(output,times-1,k+1,times2);
}
}
but I couldn't print the shape requested
Try this.
static void shape(PrintWriter output, int size, int index) {
if (index >= size)
return;
char[] buffer = new char[size];
Arrays.fill(buffer, ' ');
buffer[index] = buffer[size - index - 1] = 'X';
output.println(new String(buffer));
shape(output, size, index + 1);
}
and
try (PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out))) {
shape(output, 11, 0);
}
Just change
int arr[] = new int[times]
to
int arr[] = new int[times2]
where times2 is the width of a single row.
However a more cleaner way would be:
public class InputTest {
private static void FCITshape(int times, int k,int times2) {
if (times < 0) {
return;
} else {
for (int i = 0; i <= times2; i++) {
if (i == times)
System.out.print("X");
else if (i == k)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
FCITshape(times - 1, k + 1, times2);
}
}
public static void main(String[] args) {
FCITshape(10, 0, 10);
}
}
Regards.
With recursion
Now just call printX(0, 10);
public static void printX(int x, int l) {
if (x <= l) {
if (x < l / 2) {
for (int i = 0; i < x ; i++) {
System.out.print(" ");
}
} else {
for (int i = 0; i < l - x; i++) {
System.out.print(" ");
}
}
System.out.print("x");
if (x < l / 2) {
for (int j = 0; j < l - x * 2 - 1; j++) {
System.out.print(" ");
}
} else {
for (int j = 0; j < (x * 2 - l) - 1; j++) {
System.out.print(" ");
}
}
if (x != l / 2) {
System.out.print("x");
}
System.out.println();
printX(x + 1, l);
}
}

Resources