2

I have written the following method to find the location/index of the smallest number within the array.

private static int indexOfMin( int[] a, int cnt )
    {
        int loc = 0;//the variable that will hold the index position
        int min = a[loc];//the variable that will compare the value of loc against its location
        for (int i = 1; i < a.length; i++)
        {
            if (a[i] < min )//if value is less
            {
               min = a[i];// make value of i equal to min
               loc = i; loc takes on value of the index of the value of min
            }
       }
       return loc ;
    }

Instead of returning the location of the smallest int, it returns the location of the last int. How do I find the location of the smallest int and return it into int loc?

FURTHER EDITS: This is the program in it's entirety. The other two methods I'm still working on. So ignore them.

public static void main (String[] args) throws Exception
    {
        final int CAP = 20; // capacity
        Scanner infile = new Scanner( new File(args[0]) );
        int[] arr = new int[ CAP ];
        int count = 0;

        while ( count < arr.length && infile.hasNextInt() )
        {
            arr[ count ] = infile.nextInt();
            count++;
        }
        infile.close();
        printArray( arr, count );

        // this method is given to you as as. don't modity it
        int minVal = minOf( arr, count );
        System.out.println( "Smallest number is: " + minVal);

        // YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMin METHOD
        int indOfMin = indexOfMin( arr, count );
        System.out.println( "Smallest number is located at index position: " + indOfMin );

        // YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR maxOf METHOD
        int maxVal = maxOf( arr, count );
        System.out.println( "Largest number is: " + maxVal);

        // YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMax METHOD
        int indOfMax = indexOfMax( arr, count );
        System.out.println( "Largest number is located at index position: " + indOfMax );

    } // END main

    // GIVEN AS IS - DO NOT MODIFY
    private static int minOf( int[] a, int cnt )
    {
        int min = a[0];
        for ( int i=0 ; i<cnt ; i++ )
        {
            if (a[i] < min)
                min = a[i];
        }
        return min;
    }

    // YOU WRITE  DEFINTION OF indexOfMin
    // returns the INDEX of the min value NOT the min value itself
    private static int indexOfMin( int[] a, int cnt )
    {
        int loc = 0;
        int min = a[loc];
        for (int i = 1; i < a.length; i++)
        {
            if (a[i] < min )
            {
               min = a[i];
               loc = i;
            }
       }
       return loc ;
    }

The date file contains the following information:

86 95 84 94 32 8 56 51 98 20 90 1 75 6 21

7
  • 1
    post the reproducible code, there is nothing wrong in first method you posted, second version is buggy Commented Jul 30, 2014 at 19:46
  • I might be missing something, but the first method looks correct. Commented Jul 30, 2014 at 19:46
  • 2
    What is the purpose of cnt and why is it ignored? Commented Jul 30, 2014 at 19:47
  • 2
    Format, comment and explain your code. Help us help you. Commented Jul 30, 2014 at 19:48
  • Why do you return when a value smaller than the first is found (second code)? Commented Jul 30, 2014 at 19:57

6 Answers 6

2

Based on your comments and edit, I think you wanted

private static int indexOfMin(int[] a, int cnt) {
  int loc = 0;
  int min = a[loc];
  for (int i = 1; i < cnt; i++) {
    if (a[i] < min) {
      min = a[i];
      loc = i;
    }
  }
  return loc;
}

Then to verify,

// this method is given to you as as. don't modity it
int minVal = minOf( arr, count );
System.out.println( "Smallest number is: " + minVal);

// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMin METHOD
int indOfMin = indexOfMin( arr, count );
System.out.println( "Smallest number is located at index position: " + indOfMin);
if (arr[indOfMin] == minVal) {
  System.out.println("Min value passed");
} else {
  System.out.println("Min value failed");
}
Sign up to request clarification or add additional context in comments.

2 Comments

IT WORKED! But why was a.length incorrect and cnt correct?
@WeekzGod It's keeping a count for a reason. The array is initialized with a much larger size int[] arr = new int[ CAP ]; as an optimization (and thus the internal length is always CAP, you're using count for that reason). You put 13 elements in a 20 element array, so the last 7 elements are all 0 (and thus smaller then your smallest element).
1
int[] arr = {1, 5, 3, 4, 0, 9};
System.out.println(indexOfMin(arr));

Prints:

4

This is absolutely correct, because the index of an array starts with 0

1 Comment

It didn't work for me. With my test file it printed the last location which is a[14], not the correct location which is a[11].
0

The first method posted works.

You do not have a problem.

You might have forgotten that indexes start at 0 and thus interpreted the results as being wrong?

3 Comments

nah..it goes all the way to the end. not to the right index location
is it my computer then?
No. But I have insufficient information to tell you what is wrong. Why don't you post a complete file that can compile and be run, including the test data array and the output?
0

As stated above, your first segment of code is working fine.

Arrays in java start at index = 0.

By the looks of it, cnt is supposed to be the length of the array of data you are passing, and it can be used as a substitute for a.length (although passing the extra data is very unnecessary).

In the second segment of code, you return an index before completing the whole loop (potentially). This will stop once you get to the first item that is smaller than a[0] and return that location (which probably occurs at index 3 in your case).

For future reference, it will be helpful for us to know the data that you are testing with.

1 Comment

I have tested using your data and method and got index = 11. Again, your code is working.
0

the first code is correct.you can still remove cnt which was never used.2nd one is absolutely wrong.

import java.util.Scanner;

public class small {

private static int indexOfMin( int[] a ,int cnt)

{
   int loc=0;
    int min = a[0];
    for (int i = 1; i <cnt; i++)
    {
        if (a[i] < min )
        {
           min = a[i];
           loc = i;
        }
   }
   return loc ;
}
public static void main(String args[]){
    Scanner s= new Scanner(System.in);
    System.out.println("how many numbers do you want to enter:");
    int n=s.nextInt();
    int a[]=new int[n];
    System.out.println("enter the numbers:");
    for(int i=0;i<n;i++){
      a[i]=s.nextInt();
    }
    int p=indexOfMin(a,n);
    System.out.println((p+1)); //p+1 as we have taken location same as i which starts with 0
 }
}

how many numbers do you want to enter:7

enter the numbers: 34 45 33 234 123 116 555

the location of the smallest no is:3

I hope u find it helpful.

Comments

-1

Why don't you use Arrays.sort() and return the first element of the array?

//Snippet
void minInArray(){
    int[] arr = new int[]{55,42,11,20,584,63,21,27,84,96,32,30};
    int[] cArr = Arrays.copyOf(arr, arr.length);

    Arrays.sort(cArr);
    int idx = Arrays.asList(arr).indexOf(cArr[0]);
    String s = new StringBuilder("The min value is: ")
               .append(cArr[0])
               .append(" located at index: ")
               .append(idx)
               .toString();
    System.out.println(s);
}

6 Comments

because sorting is overkill here
I don't know how much overkill could be there... I mean to me it's easier: Arrays.sort(myArray); and then Arrays.asList(myOriginalArray).indexOf(myArray[0]); is even good for reading.
While I generally agree with the fact that you shouldn't do premature optimizations, but there's no way I could get behind sorting an array, just to find the smallest element.
Oh dear. You even have to copy the array here. And this isn't even any more readable, than just looping and saving the smallest element...
Well, to me it's easier since there are 0 looping, you're focusing on what it matters, to find the lowest value with and its index. I don't see why is this so bad, unless you're trying to use huge arrays (millions of elements). And here I'm only using 6 lines of code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.