HI, I have now for more than 24 hours tried to figure out how I return the index number of the second smallest integer in an unsorted array.

Some how, I do not get the index number returned, can any one see what I´m missing?

As the program runs now, it returns the value of the second smallest integer in an array, but I can´t make the program return the index number in the array.

Thanks in advance

public class SecondSmallest {

	public static void main(String[] args) {
		
		System.out.println("Næstmindste værdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {1,2,3,4,5})));
	}
	public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
		if (values.length < 2) {
			throw new IllegalArgumentException("Der skal være mindst to værdier i arrayet af typen int");
		}
			
			int min;// declare variable
			int secondMin;// declare variable
			// Estblish relation between min and secondMin in the array
			if (values[0] < values[1]) { 
		        min = values[0];
		        secondMin = values[1];
		    }// end of if 
			else {
		        min = values[1];
		        secondMin = values[0];
		    }// end of else
		    
			for (int i = 0; i < values.length; i++) {
		        if (values[i] <= min) {
		            secondMin = min;
		            min = values[i];
		        } 
		        else if (values[i] < secondMin) {
		            secondMin = values[i];
		            values[i]= secondMin;
		        }       
		    }//end of for
			
		    for (int i = 0; i < values.length; i++) {
		    	if ( values[i] == secondMin ) {
		    		values[i]=secondMin;
		    		//secondMin = i; //Should retrieve indexnumber of secondMin
		    		return secondMin;	
		    }// end of if
		   //  return i;
	     }// end of	forloop
			return secondMin;
		    	
	}// end of static int
}// end of class
Attachments
public class SecondSmallest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// TODO Auto-generated method stub

		System.out.println("Nstmindste vrdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {33,32,31,30,29})));
	}
	public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
		if (values.length < 2) {
			throw new IllegalArgumentException("Der skal vre mindst to vrdier i arrayet af typen int");
		}
			
			int min;// declare variable
			int secondMin;// declare variable
			// Estblish relation between min and secondMin in the array
			if (values[0] < values[1]) { 
		        min = values[0];
		        secondMin = values[1];
		    }// end of if 
			else {
		        min = values[1];
		        secondMin = values[0];
		    }// end of else
		    
			for (int i = 0; i < values.length; i++) {
		        if (values[i] <= min) {
		            secondMin = min;
		            min = values[i];
		        } 
		        else if (values[i] < secondMin) {
		            secondMin = values[i];
		            values[i]= secondMin;
		        }       
		    }//end of for
			
		    for (int i = 0; i < values.length; i++) {
		    	if ( values[i] == secondMin ) {
		    		values[i]=secondMin;
		    		//secondMin = i; //Should retrieve indexnumber of secondMin
		    		return secondMin;	
		    }// end of if
		   //  return i;
	     }// end of	forloop
			return secondMin;
		    	
	}// end of static int
}// end of class

The answer is very simple. You declare 2 variables:
"min"
"secondMin"
that hold the values of the "min" and "second min". So why don't you declare 2 more values that will hold the indexes:

"minIndex"
"secondMinIndex"

int min;// declare variable
int secondMin;// declare variable

int minIndex;// declare variable
int secondMinIndex;// declare variable

.....

if (values[0] < values[1]) { 
		        min = values[0];
		        secondMin = values[1];

                       minIndex = 0;
                       secondMinIndex = 1;
		    }// end of if 
			else {
		        min = values[1];
		        secondMin = values[0];

                       minIndex = 1;
                       secondMinIndex = 0;
		    }// end of else

.....

if (values[i] <= min) {
		            secondMin = min;
		            min = values[i];
                       
                       secondMinIndex = minIndex ;
                       minIndex = i;
		        } 
		        else if (values[i] < secondMin) {
		            secondMin = values[i];
		            
// This wrong. You don't want to change the values of the array.
// just save the values[i] to the secondMin variable
//values[i]= secondMin;

                       secondMinIndex = i ;
		        }

Look at my comments in the above code

javaAddict's method is probably the best. If you are going to want additional numbers/indexes--like the 3rd or 4th smallest--you may just want to sort your array. Then the "smallest" numbers will have index of "n-1". Second smallest will have index of "2-1 = 1". Third smallest will have index of "3-1 = 2". Smallest will have index of "1-1 = 0"...etc. Guess it depends on your goal.

Thank you very much to both javaAddict and to cgeier,

I have also tried the sorting, but my problem is that I can´t understand where the "shift" or conversion from assigning the values of the elements in the array, to index numbers of the relevant numbers in the array.

I guess it is some kind of basic knowledge I don´t get.

So far, even with 4 variables declared, as javaAddict illustrated, I still don´t get "system.out" to print the index number.

But still working on it - with 4 variables ;-)

If you want to sort your list but do not want to write the sorting method yourself, then you can create an ArrayList, add each of your Integers to the ArrayList, then use Collections.sort(yourArrayList) which will sort it for you. For more information on those concepts, you can look at the Javadocs for each. Here's a small example

//This assumes you already have an array of ints
//called myIntArray set up.
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < myIntArray.length; i++){
    list.add(myIntArray[i]);
}
Collections.sort(list);

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html

However, I would strongly suggest that you learn how to write at least one simple sorting method yourself, this is the easiest way to do it but not the one that will help you learn the most.

Thanks BestJewSinceJC,
but the goal is to write, or use, some kind of known sorting algorithmne - and to learn ;-) so I´ll keep trying to solve the problem for an Array and not an ArrayList. The turning point is how to translate the value of the element to the index number of the elemen,t which I do not get.

The best way to "translate the value of the element to the index" is to simply keep track of what index you are looking at. To do a "swap" (switch two values in the array) all you need are three pieces of information: The two indexes you want to swap, and a temporary variable to hold the value of the overwritten index.

So

array[5] = array[4];
array[4] = array[5];

Doesn't work because you just overwrote array[5]. So you'd do this instead:

int temp = array[5];
array[5] = array[4];
array[4] = temp;

That probably doesn't help.... feel free to ask some questions about sorting, we'll all be glad to help.

Below is an example of how to use 4 variables. It's only been tested with the defined integer array. I'm not saying whether it's the best way to do it or not, I worked with what you had. I did it quickly so double check that it works for all cases. Remember array indexes in Java start with "0".

If you use an array and sort it from lowest to highest, the 2nd smallest integer index will always be "1" (with 2 or more integers) No "testing" required. It just always is.

public class SecondSmallest {
 	public static void main(String[] args) {
 		System.out.println("Næstmindste værdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {44,35,62,5,22,66})));
	}
	public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
		if (values.length < 2) {
			throw new IllegalArgumentException("Der skal være mindst to værdier i arrayet af typen int");
		}
 			int min;// declare variable
			int secondMin;// declare variable
            int minIndex;
            int secondMinIndex;
			// Estblish relation between min and secondMin in the array
			if (values[0] < values[1]) {
		        min = values[0];
                                        //take index from above '0' (min = values[0]) and save as minIndex
                                        minIndex = 0;

		        secondMin = values[1];
                 //take index from above '1' and save as minIndex
                secondMinIndex = 1;

		    }// end of if
			else {
		        min = values[1];
                minIndex = 1;
		        secondMin = values[0];
                secondMinIndex = 0;
		    }// end of else

 			for (int i = 0; i < values.length; i++) {
		        if (values[i] <= min) {
		            secondMin = min;
                    secondMinIndex = minIndex;
		            min = values[i];
		        }
		        else if (values[i] < secondMin) {
		            secondMin = values[i];
                    secondMinIndex = i; 
		            values[i]= secondMin;

		        }
		    }//end of for
 		    for (int i = 0; i < values.length; i++) {
		    	if ( values[i] == secondMin ) {
		    		values[i]=secondMin;
                    secondMinIndex = i;
		    		//secondMin = i; //Should retrieve indexnumber of secondMin
		    		//return secondMin;
                    
		    }// end of if
		   //  return i;
	     }// end of	forloop
			//return secondMin;
            return secondMinIndex;

 	}// end of static int
}// end of class

Actually your initial code was just searching for the 1st and 2nd number.
If you want sorting, then the algorithm is entire different.
It depends on your specifications. I mean the easiest way to do this, is first to sort the array and then you will know that the 1st number is the first element of the array, the 2nd number is the second element of the array.
Sorting is easy. It is more difficult to find the second number without sorting, which why I was referring to your specifications. Maybe you were asked to find the 1st and 2nd without sorting

HI, I have now for more than 24 hours tried to figure out how I return the index number of the second smallest integer in an unsorted array.

Some how, I do not get the index number returned, can any one see what I´m missing?

As the program runs now, it returns the value of the second smallest integer in an array, but I can´t make the program return the index number in the array.

Thanks in advance

public class SecondSmallest {

	public static void main(String[] args) {
		
		System.out.println("Næstmindste værdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {1,2,3,4,5})));
	}
	public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
		if (values.length < 2) {
			throw new IllegalArgumentException("Der skal være mindst to værdier i arrayet af typen int");
		}
			
			int min;// declare variable
			int secondMin;// declare variable
			// Estblish relation between min and secondMin in the array
			if (values[0] < values[1]) { 
		        min = values[0];
		        secondMin = values[1];
		    }// end of if 
			else {
		        min = values[1];
		        secondMin = values[0];
		    }// end of else
		    
			for (int i = 0; i < values.length; i++) {
		        if (values[i] <= min) {
		            secondMin = min;
		            min = values[i];
		        } 
		        else if (values[i] < secondMin) {
		            secondMin = values[i];
		            values[i]= secondMin;
		        }       
		    }//end of for
			
		    for (int i = 0; i < values.length; i++) {
		    	if ( values[i] == secondMin ) {
		    		values[i]=secondMin;
		    		//secondMin = i; //Should retrieve indexnumber of secondMin
		    		return secondMin;	
		    }// end of if
		   //  return i;
	     }// end of	forloop
			return secondMin;
		    	
	}// end of static int
}// end of class

Hey, in your own code, instead of doing
for (int i = 0; i < values.length; i++)
{
.
.
.
}

just try this and
int i;
for (i = 0; i < values.length; i++)
{
.
.
.
}
return i;


EXPLANATION
-------------------
When you declare "int i" inside "for" loop(as in for (i = 0; i < values.length; i++)), you are creating a local variable which exist only in the scope of "for" loop. In other words, it is not visible outside the loop.
If you use the suggested method "int i", "i" will be visible outside the "for" loop as well.

Remaining function seems alright but, lots of code is redundant. Think over it.

Hello every one,
this just to say that I´m still working on it, and to confirm that it is the index number of an unsorted array.
Right now I´m trying out some thing with temp variables and variables for minIndex and secondMinIndex.

And when I get back to night, I´m gonna test the advice with declare int i outside the for-loop - sounds like a solution but no time to test right now.

Thanks a lot :-)

Hey check this function

public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
	if (values.length < 2)
		throw new IllegalArgumentException("Your message here");
	int min = values[0];		// Largest possible integer in Java
	int secondMinIndex;			// Need not be initialised.

	int i;
	for(i=1;i<values.length;i++)	// Finding minimum first
		if(values[i] < min)
			min = values[i];

	if(values[0] < values[1])	// The selected index should not be minimum
		secondMinIndex = 1;
	else
		secondMinIndex = 0;
	for(i=0;i<values.length;i++)	// Finding second smallest's index
		if(values[i] < values[secondMinIndex] && values[i] != min)
			secondMinIndex = i;

	return secondMinIndex;
}

I tried all possible arrays and it worked

Hi harsh2327,
have now tried your solution and you are right , it works. thank you.
Guess it is a typical beginner error/problem declaring variables in the wrong places making them unaccessible ;-)

Thank you very much to everybody for helping me, I´m now gonna mark this thread as solved.

public static int indexOfSecondSmallest(int...values) {
    int[] rankedIndices = new int[] {-1,-1};
    for(int idx=0; idx < values.length; idx++) {
      if(-1 == rankedIndices[1] || values[idx] < values[rankedIndices[1]]) {
        if(-1 == rankedIndices[0] || values[idx] < values[rankedIndices[0]]) {
          rankedIndices[1] = rankedIndices[0];
          rankedIndices[0] = idx;
        }
        else {
          rankedIndices[1] = idx;
        }
      }
    }
    return rankedIndices[1];
  }
This question has already been answered. Start a new discussion instead.