Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Find Min/Max Values in an array, then return the min/max values in a new array

Having some trouble figuring out why this ain't working.

Making a method that takes in an integer array full of numbers and I'm supposed to return the smallest and largest number in the array.

Upon finding the min and max I'm supposed to return it in a new integer array.

My method:
Code
public static int[] minmax(int[] a) {
        int[] minmaxA = new int[2];
        int max = 0;
        int min = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] > max) {
                max = a[i];
            }
            if (a[i] < min) {
                min = a[i];
            }
        }
        minmaxA[0] = min;
        minmaxA[1] = max;
        return minmaxA;
    }

A test case code (Using jUnit):
Code
assertArrayEquals(new int[] { 1, 9 }, ArrayUtil.minmax(new int[] { 1, 2, 7, 9 }));
[Image: DTc14yu.png]
Your code is working, your test case is incorrect because you are passing an array from 1-9. When you are testing for min value 1 is not less than 0, so the min value would stay as 0.
Try this.

Code
public static int[] minMax(int[] numbers) {
        int minNum = numbers[0], maxNum = numbers[0];

        for (int num : numbers) {
            if (num < minNum)
                minNum = num;

            if (num > maxNum)
                maxNum = num;
        }

        return new int[] {minNum, maxNum};
    }
(Feb 27, 2016 12:33 PM)+Haze Wrote:  Try this.

Code
public static int[] minMax(int[] numbers) {
        int minNum = numbers[0], maxNum = numbers[0];

        for (int num : numbers) {
            if (num < minNum)
                minNum = num;

            if (num > maxNum)
                maxNum = num;
        }

        return new int[] {minNum, maxNum};
    }
god bless your soul nigga
[Image: DTc14yu.png]
Int[] intarr = new Int[10];
intarr[0] = 10;
intarr[1] = 1;
int imax = 0;
for( int i ; intarr )
if( i > imax )
imax = i;
The reason this method isn't working properly is that you have set the min and max equal to zero.
So you are basically comparing if each number in the array is greater than or less than zero which doesn't make any sense whenever you are trying to find the min and max, right? I'm not going to take the time to compile and run this, but i believe your max would be the last integer in your array because 9 IS greater than zero and the min will be zero because none of the integers in your array is less than zero. The solution to this problem is to set the min and max to the first integer of the array.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by gurlhackerclubMay 19, 2020 05:18 PM 8 260 May 19, 2020 05:18 PM
Last Post: k1r3n
[C] by SIM-2362662Apr 23, 2020 07:06 PM 11 374 Apr 23, 2020 07:06 PM
Last Post: dracx
[C] by TralenSep 9, 2017 05:13 PM 7 211 Sep 9, 2017 05:13 PM
Last Post: 0xDEAD10CC