samedi 25 avril 2015

Finding the largest number in an array of integers


I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and 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];
        for (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];
        for (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 the number of elements in your list: ");
    int x = scan.nextInt();
    if(x>1 || x<100){
        for (int i=0; i<=(x-1); i++){
            System.out.print("Enter your 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 be less than 100");


}

}


Aucun commentaire:

Enregistrer un commentaire