java - Finding the largest number in an array of integers -


i trying recursively find largest element in array. user has input number of elements array have. error if list not have element larger number of elements in list, output of largest number number of elements in list. eg: array of 5 integers containing {1 1 1 2 3}. answer 5 , not 3.

import java.util.*;  public class test7 {      public static int findlargest(int[] a, int max) {          int i=0, j=0, tempmax=0;         if (a.length == 1) return a[0]>max ? a[0]:max;         else if(max < a[i]){             max = a[i];             int[] temparr = new int[a.length -1];             (i=1; i<a.length; i++){                 temparr[j] = a[i];                 j++;             }             tempmax = findlargest(temparr, max);             return tempmax;         }         else{             int[] temparr = new int[a.length -1];             (i=1; i<a.length; i++){                 temparr[j] = a[i];                 j++;             }             tempmax = findlargest(temparr, max);             return tempmax;         } }        public static void main(string[] args) {         int[] values = new int[100];          scanner scan = new scanner(system.in);         system.out.println("enter number of elements in list: ");         int x = scan.nextint();         if(x>1 || x<100){             (int i=0; i<=(x-1); i++){                 system.out.print("enter number: ");                 system.out.println();                 values[i] = scan.nextint();             }                    system.out.println();             system.out.println("the largest number is: "+findlargest(values, x));         }         else system.out.println("the maximum number of elements must less 100");       } } 

you call method with:

system.out.println("the largest number is: "+findlargest(values, x)) 

this tells assume largest number x , try find in list greater that. of course, produces exact problem described.

in general, when finding maximum number, want initialize candidate lowest number possible, or first number in array.

if initialize lowest number possible (integer.min_value) start algorithm, first number bigger , chosen next candidate maximum.

if initialize first item in array, if number highest, , good. if not, when encounter next higher number, become candidate, , good.

which 1 choose (and depends on whether empty array possible), thing remember never select initial candidate might greater elements in array.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -