3

I need to make a programm in java with the selection sort algorithm. So i tried this to do that but the code doesn't works.

3
  • 1
    Read this article for tips on debugging your code. Commented Apr 23, 2020 at 15:20
  • I'm pretty sure that min should be storing an array index, not a value of the element, so that you can actually swap two array elements after the inner for loop is done Commented Apr 23, 2020 at 15:22
  • Do not delete the relevant code from your question, it invalidates answers Commented Apr 23, 2020 at 15:46

3 Answers 3

2

Problem with this code is that it doesn't swap numbers. Instead, it replaces array[i] with the minimum number found.
You can modify your loop like this to do the swapping.

        for (int i = 0; i < array.length; i++) {

          int minIndex = i;
          for (int j = i; j < array.length; j++) {

              if (array[j] < array[minIndex]) {
                  minIndex = j;
              }

          }
          if (array[minIndex] != array[i]) {
            int wert = array[minIndex];
            array[minIndex] = array[i];
            array[i] = wert;

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

Comments

1

For selection sort use this method

public static void selectionSort(int[] arr) {

    for (int i = 0; i < arr.length - 1; i++) {
        int index = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[index]) {
                index = j;//searching for lowest index
            }
        }
        int smallerNumber = arr[index];
        arr[index] = arr[i];
        arr[i] = smallerNumber;
    }

}

Comments

0

If you need an ascend order just use:

Arrays.sort(array) from java.util library

But if you need to sort descending I'd suggested to reffer to:

https://www.baeldung.com/java-sorting-arrays

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.