简体   繁体   中英

Java sorting algorithm problems

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.

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;

          }
        }

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;
    }

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM