0

I use the selection method to solve this problem, but I meet some problems. After seeing answer for it, I found two bugs in my program and then fix it. I am confused about why these two bugs occur, can anyone give me a hand to explain them?

Here is my code:

import java.util.Scanner;
public class JavaTest{
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    int[] myList = new int[5];
    for (int i = 0; i < 5; i++){
        myList[i] = input.nextInt();
    }

    for (int i = 0; i < 4; i++){
        int j = 0;

        // Why do I need to put this outside inner for loop?
        int smallest = myList[i];

        // Why do I need to give the value of i to index after i increase by 1?
        int index = i;

        for (j = i + 1; j < 5; j++){
            if (smallest > myList[j]){
                smallest = myList[j];
                index = j;
            }
        }

        if (index != i){
            myList[index] = myList[i];
            myList[i] = smallest;
        }

    }

    for (int i = 0; i < 5; i++){
        System.out.print(myList[i] + " ");
    }

    input.close();
}
}
4
  • could you please provide a little more information? Commented Mar 23, 2015 at 23:33
  • @immibis he wrote the bugs in the comments inside his code.... Commented Mar 23, 2015 at 23:45
  • 1
    @OldFox those aren't bugs, they're questions... Commented Mar 23, 2015 at 23:46
  • @immibis from his questions it's clearly that "int smallest = myList[i];" was inside the inner loop and "int index = i;" wasn't changed after each iteration Commented Mar 23, 2015 at 23:52

1 Answer 1

1

Selection algorithm is an algorithm for finding the kth smallest number in a list or array.

Each iteration your algorithm find the smallest number i to myList.length:

First iteration is between 0 to 4

Second iteration is between 1 to 4 and etc...

    // Why do I need to put this outside inner for loop?
    int smallest = myList[i];

After the first iteration the value of "smallest" will be the real smallest number in the list instead of the smallest in indexes 1 to 4, and then the inner loop won't do anything.

    // Why do I need to give the value of i to index after i increase by 1?
    int index = i;

you initialize the index to the current position of your (suspected)smallest number. if the current value of "smallest" is the smallest number in the iteration then the second "for loop" won't do anything.

and then the condition:

(index != i)

will be true even though it shouldn't

Sign up to request clarification or add additional context in comments.

Comments

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.