How do I iterate through an array at a specific point. Using just the base functions for an array.
I'm doing the MOOC from Helenski and I'm stuck on example 104.3 in week 6. I'm supposed to build the sort function but I'm stuck at the third part where it says to show the index of the smallest value starting from a specific point. I've been trying different solutions but can't get it to work.
I want to use my smallest function on just a subsection of the array then I can just do what I did for my indexOfTheSmallest function.
My method is called indexOfTheSmallestStartingFrom its on the bottom.
package problem104_sorting;
public class Problem104_Sorting {
public static void main(String[] args) {
int[] values = {-1, 6, 9, 8, 12,};
System.out.println(indexOfTheSmallestStartingFrom(values, 1));
System.out.println(indexOfTheSmallestStartingFrom(values, 2));
System.out.println(indexOfTheSmallestStartingFrom(values, 4));
}
public static int smallest(int[] array){
int a = 0;
for(int i =0; i<array.length; i++){
int b = array[i];
for(int numb : array){
if(numb < b){
b = numb;
}
}
a = b;
}
return a;
}
public static int indexOfTheSmallest(int[] array){
int a = smallest(array);
int z =0;
for(int i=0; i<array.length; i++){
if(array[i] == a){
z=i;
}
}
return z;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index){
int b = array[index];
for(int c = index; c<array.length; c++){
if(b<array[c]){
b=c;
}
}
return b;
}
}
Posted Aug 20, 2019, 5:05 PM UTC
32
First, when you iterate through collections, you typically use the variable i. Also, you have no bounds checking at all, which is easy to add.
I believe your only real problem is your logic is reversed. Check the
ifcondition.Good luck!