Whenever I give the size of array more than 3, my program gives me StackOverflowError.
package database;
import java.util.Scanner;
public class The_Maximum_Subarray {
int a[];
public The_Maximum_Subarray(int size) {
a=new int[size];
}
public int maxsubArray(int[] a,int li,int ui)
{
if(ui ==li)
return a[li];
int m=(ui-li)/2;
int leftMaxSubarray=maxsubArray(a, li, m);
int rightMaxSubarray=maxsubArray(a, m+1, ui);
int leftSum=0,rightSum=0,sum=0;
for(int i=m;i>=li;i--)
{
sum+=a[i];
if(sum>leftSum)
leftSum=sum;
}
sum=0;
for(int i=m+1;i<=ui;i++)
{
sum+=a[i];
if(sum>rightSum)
rightSum=sum;
}
sum=leftSum+rightSum;
if(rightMaxSubarray>=leftMaxSubarray && rightMaxSubarray>=sum)
return rightSum;
else if(leftMaxSubarray>=rightMaxSubarray && leftMaxSubarray>=sum)
return leftSum;
else
return sum;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
The_Maximum_Subarray obj=new The_Maximum_Subarray(size);
for(int j=0;j<size;j++)
obj.a[j]=sc.nextInt();
System.out.println(obj.maxsubArray(obj.a, 0, size-1));
}
}
Can anyone tell me why it's giving me this exception for this small size array ?
From your question:
Can anyone tell me why its giving me this exception for this small size array ?
For the part Why it is causing??
According to the java language specifications for java.lang.StackOverflowError, this error occurs when an application recurses too deeply.
This recursion results in filling the stack and it tries to exceed the limit of the stack which is Xs.
Take a simple example:
class StackOverflowDemo {
private void causeOverflow(int i) {
causeOverflow(i);
System.out.println(i);
}
public static void main(String args[]) {
StackOverflowDemo demo = new StackOverflowDemo();
demo.causeOverflow(5);
}
}
Here, the System.out.println(i) will be called recursively i.e it will be pushed to the stack when it is called.
Related
In my java program I want to perform stack operation like push and pop. I also want to push string in stack operation but when I try to push string. I get error mentioned in screenshot. How should I change push method in order to run the program successfully.
code ::
public class DataStack {
private static final int capacity = 3;
String arr[] = new String[capacity];
int top = -1;
public void push(String pushedElement) {
if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
printElements();
} else {
System.out.println("Stack Overflow !");
}
}
public void pop() {
if (top >= 0) {
top--;
System.out.println("Pop operation done !");
} else {
System.out.println("Stack Underflow !");
}
}
public void printElements() {
if (top >= 0) {
System.out.print("Elements in stack : ");
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
DataStack stackDemo = new DataStack();
stackDemo.push("china");
stackDemo.push("india");
stackDemo.push("usa");
}
}
Error::
Your push() method and underlying arr variable should be of String type.
String arr[] = new String[capacity];
public void push(String pushedElement) {
...
}
Your array is declared to store only integers . Not to mention, the stackDemo.push method also declared to take in only int arguments.
int arr[] = new int[capacity];
public void push(int pushedElement) {
you should try pushing in integers.
stackDemo.push(1);
stackDemo.push(2);
stackDemo.push(3);
I am just starting to learn recursion and was able to use it write a simple factorial program without much of a problem. Now I am trying to write a recursive method that writes an array in reverse order but I can't figure out what I'm doing wrong. What am I missing? Thank you.
import java.io.*;
public class Recursion {
public static void main(String[] args) throws IOException{
int myArray[] = {1,2,3,4,5,6,7,8,9,10};
}
public static void reverseDisplay(int[] ary, int position){
if(position > 0)
System.out.print(ary[position]);
reverseDisplay(ary, position - 1);
}
}
You do not call your recursion method.
You have an endless recursion because reverseDisplay() is always
being executed due to missing enclosing brackets.
Also your stop condition has to be >= 0 because the first index of an array is 0.
Your method should read:
import java.io.IOException;
public class Recursion {
public static void main(String[] args) throws IOException{
int myArray[] = {1,2,3,4,5,6,7,8,9,10};
reverseDisplay(myArray, myArray.length -1);
}
public static void reverseDisplay(int[] ary, int position){
if(position >= 0) {
System.out.print(ary[position]);
reverseDisplay(ary, position - 1);
}
}
}
When doing recursion you need something called a base case. You need the base case to end the recursion or you will get a stack overflow.
You might try something like this. The return statement stops the recursion from being endless.
public static void reverseDisplay(int[] ary, int position){
if(int == -1)
return;
System.out.print(ary[position]);
reverseDisplay(ary, position - 1);
}
Try:
import java.io.*;
public class Recursion {
public static void main(String[] args) throws IOException{
int myArray[] = {1,2,3,4,5,6,7,8,9,10};
reverseDisplay(myArray,0);
}
public static void reverseDisplay(int[] ary, int position){
if(position == ary.length){
return;
}
reverseDisplay(ary, position + 1);
System.out.print(ary[position]);
}
}
If position == ary.length you finish the recursion, else you call reverseDisplay recursively and after that print the current position of ary.
I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}
Is there a hack to print the first n fibonacci numbers without calling a loop
for(int i=1; i<n; i++)
System.out.println(computeF(n));
from the main program?
public static int computeF(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return computeF(n-1)+computeF(n-2);
}
}
There might be a way to print the intermediate values in recursion which will print the fibonacci numbers.
You could use tail recursion.
public class Fid
{
static int n1=0;
static int n2=1;
static int nex=0;
public static void fb(int n)
{
if(n<10)
{
if(n==0)
{
System.out.print(" "+n);
n++;
fb(n);
}
else
if(n==1)
{
System.out.print(" "+n);
n++;
fb(n);
}
else{
nex=n1+n2;
System.out.print(" "+nex);
n1=n2;
n2=nex;
n++;
fb(n);
}
}
}
public static void main(String[] args)
{
fb(0);
}
}
using recursion:-
class FibonacciRecursion
{
private static int index = 0;
private static int stoppingPoint = 9;
public static void main (String[] args)
{
int n1 = 0;
int n2 = 1;
fibonacciSequence(n1, n2);
}
public static void fibonacciSequence(int n1, int n2)
{
System.out.println("index: " + index + " -> " + n1);
// make sure we have set an ending point so this Java recursion
// doesn't go on forever.
if (index == stoppingPoint)
return;
// make sure we increment our index so we make progress
// toward the end.
index++;
fibonacciSequence(n2, n1+n2);
}
}
//Java program to print Fibonacci Series up to n terms given by user without using loop
import java.util.* ;
public class Fibonacci
{
public static void main(String[] arguments)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the no of terms :");
int no_of_terms= s.nextInt(),a=1,b=0,c=0,count=1;
System.out.print("0 ");//printing the first term
fib(no_of_terms,a,b,c,count);}
public static void fib(int no_of_terms,int a,int b,int c,int count)
{
//when value of count will be equal to the no of terms given by user the program will terminate
if (count==no_of_terms)
System.exit(0);
else
{
count++;
System.out.print(a+" ");
c=b;
b=a;
a=b+c;//calculating the next term
fib(no_of_terms,a,b,c,count);//calling the function again with updated value
}
}
}
import java.util.*;
public class Fibonacci{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no.");
int n= sc.nextInt(),a=1,b=0,c=0;
num(n,a,b,c);
}
public static void num(int n,int a,int b,int c){
if(a<=n){
System.out.println(a);
c=b;
b=a;
a=b+c;
num(n,a,b,c);
}
}
}