Need advice on selection sort/method overloading not working completely correctly

Viewed 25

I am still pretty new to coding in Java/Eclipse, so sorry if this is an easy error to spot. I'm practicing method overloading for my final exam, and am attempting to put an array in ascending and descending order. I've got everything down except for one tiny problem. Only one number is out of place for the sorting, but I don't understand why. The output comes out like this -

Ascending order: [7.0, 17.0, 37.0, 27.0, 57.0, 87.0, 97.0, 647.0, 897.0] Descending order: [897, 647, 97, 87, 57, 37, 27, 17, 7]

Gonna list my code below here

import java.util.Arrays;

public class FinalExam1 {

    public static void main(String[] args) {
        
        double[] array1 = new double[9];
        int[] array2 = new int[9];
        
        array1 [0] = 7.0; array1 [1] = 647.0; array1 [2] = 897.0;
        array1 [3] = 97.0; array1 [4] = 87.0; array1 [5] = 57.0;
        array1 [6] = 27.0; array1 [7] = 37.0; array1 [8] = 17.0;
        
        array2 [0] = 7; array2 [1] = 647; array2 [2] = 897;
        array2 [3] = 97; array2 [4] = 87; array2 [5] = 57;
        array2 [6] = 27; array2 [7] = 37; array2 [8] = 17; 
        
        sort(array1);
        System.out.println("Ascending order: " + Arrays.toString(array1));
        sort(array2);
        System.out.println("Descending order: " + Arrays.toString(array2));
   }
    
    public static void sort(double[] array) {
        for (int i = 0; i<array.length - 1; i++) {
            int min = i;
            for (int j = i + 1; j<array.length; j++) {
                if (array[j]<array[min]) {
                    min = j;
                }

                double temp = array[min];
                array[min] = array[i];
                array[i] = temp;
            }
        }
    }

    public static void sort(int[] array) { 
        for(int i = 0; i < array.length - 1; i++) {
            int max = i;
        for(int j = i + 1; j < array.length; j++)
        if(array[j] > array[max]) {
            max = j;
        }
        
        int temp = array[max];
        array[max] = array[i];
        array[i] = temp;
        }
    }
}

Any help is appreciated, and sorry again if it's a stupid error.

1 Answers

You should move swap to the outer for-loop.

Here is a correct version:

public static void sort(double[] array) {
    for (int i = 0; i < array.length - 1; i++) {
        int min = i;
        for (int j = i + 1; j < array.length; j++) {
            if (array[j] < array[min]) {
                min = j;
            }
        }
        // swap
        double temp = array[min];
        array[min] = array[i];
        array[i] = temp;
    }
}
Related