Faster way to find min and max values in array

Viewed 14946

I was wondering, which way would be faster for the compiler. Using the sort or a looping method to display min value and max value. Which is a faster method for the compiler or programmer?

I included the looping method as a comment.

import java.util.Scanner;
import java.util.Arrays;

public class Day3 
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Maximum and minimum value array");
        System.out.println("--------------------------------\n");

        //variable declaration
        int amount;
        int[] integerArray;

        //set amount
        System.out.print("Enter the amount of numbers to sort: ");
        amount = scan.nextInt();
        integerArray = new int[amount];

        //input loop
        System.out.print("Enter numbers: ");
        for(int i = 0; i < amount; i++)
        {
            integerArray[i] = scan.nextInt();
        }

        System.out.print("\nHere is your array: " + Arrays.toString(integerArray) + "\n");

        Arrays.sort(integerArray);
        System.out.println("Min value = " + integerArray[0]);
        System.out.println("Max value = " + integerArray[integerArray.length - 1]);
        System.out.println("Median value = " + integerArray[(integerArray.length -1) / 2]);

        /*
        int[] arr = new int[10];
        Scanner in = new Scanner(System.in);
        int i, min=0, max=0;
        for(i=0; i<=arr.length; i++)
        {
            System.out.print("Enter any number: ");
            arr[i] = in.nextInt();          
        }
        min = arr[0];
        for(i=0; i<=9; i++)
        {
            if(arr[i] > max)
            {
                max = arr[i];
            }
            if(arr[i] < min)
            {
                min = arr[i];
            }
        }
        System.out.println("Maximum is: " + max);
        System.out.println("Minimum is: " + min);
        */

    }
}
6 Answers

Similar to other answers

public class FindMaxAndMinFromArray {
static void findMaxAndMin(int[] arrNum) {
    Arrays.sort(arrNum);//will sort original array
    System.out.println("Min number is : " + arrNum[0]);//After sorting 0 index will be min value
    System.out.println("Max Number is : " + arrNum[arrNum.length - 1]); //last index will be max value
}

public static void main(String[] args) {
    int myArr[] = { 75,10, 20,80,65, 30, 40, 50 };
    findMaxAndMin(myArr);
}
}
Related