sorting algorithm problem in Java; get wrong results

Viewed 123

Create in the class MainProgram a class method called indexOfSmallestFrom. It works similarly to the method in the previous section, but only considers the table values from a certain index forwards. In addition to the table, it receives this start index as a parameter.

In this example the first method call searches for the index of the smallest number, starting from index 0. Starting from index 0, the smallest number is -1 and its index is 0. The second method call searches for the index of the smallest value starting from index 1. In this case the smallest number is 6 and its index is 1. The third calls searches for the index of the smallest value starting at index 2. Then the smallest number is 8 and its index is 3.

the index should be printed for the smallest array. According to the int array, my output should be:

1
1
4

but i get:

1
1
3

can't figure out logically, why.

public class MainProgram {

    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};
        
        System.out.println(MainProgram.indexOfSmallestFrom(array, 0));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 1));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 2));
    }
    
    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int count = startIndex;
        int indexOf = 0;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               count++;
            }
              indexOf = count; 
        }
            return indexOf;
    }   
 
}
1 Answers

Just update indexOf when you find an element smaller than the value at the indexOf which is initially initialized as startIndex.

After iterating through all the values... return the finally updated indexOf.

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};

        System.out.println(indexOfSmallestFrom(array, 0));
        System.out.println(indexOfSmallestFrom(array, 1));
        System.out.println(indexOfSmallestFrom(array, 2));
    }

    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int indexOf = startIndex;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               indexOf = i;
            }
        }
            return indexOf;
    }   
}
Related