reverse an array in java using recursion - java

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.

Related

Recursion to print number by using return statement

I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num<=2){
rec(++num);
}
System.out.println(num);
}
}
but I want to do this with the following way.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num==2){
return;
}
rec(++num);
System.out.println(num);
}
}
Expected output:
2,1,0
but it shows:
2,1
Why does it happen?
++num increments num, which (as here) makes the code harder to understand.
Try calling rec(num + 1); instead.
You may find your terminating condition needs to be modified to:
if (num > 2)
Terminating conditions are usually the “do nothing” case, which is the case here.
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.
rec(0) prints rec(1),1
rec(1) prints rec(2),2
rec(2) prints nothing
Total output: 2,1
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.
Your if statement is also backwards.
public class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num) {
if (num < 2) {
rec(num + 1);
}
System.out.println(num);
}
class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num <= 2){
rec(num + 1);
} else return;
System.out.println(num);
}
}
++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.
When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.

Sum of Numbers Recursion

I want to display every number leading up to the variable 'number'.
Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
System.out.println(recursion(number));
}
public static int recursion(int number)
{
for (int i=0;i>number;i++)
{
return recursion(i);
}
else {
return number ;
}
}
}
You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.
Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:
void myRecursiveProgram(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
System.out.println(n); // Complete the task by printing the last number
}
Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:
void printNumbersUpToN(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1);
System.out.println(n);
}
Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.
Your code doesn't compile, you have an else without if.
What you are trying to do is something like:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
recursion(number);
}
public static void recursion(int number)
{
if (number>1)
{
recursion(number-1);
System.out.print(number);
}
else {
System.out.print(number);
}
}
}
This short code will also print the numbers right.
public void recursion(int number){
if (number>1)
recursion(number-1);
System.out.println(number);
}

StackOverflowError too early

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.

Heap Sort. What's wrong in this code?

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.

Stackoverflow error in counting the minimum number of coins to make the sum S

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

Categories

Resources