Search code examples
javaarrayssortingselection-sort

In this selection sort code i get from {8,3,5,9,2} an array answer of{2,3,3,5}


I don't understand where is the problem , I traced it and i get the correct sorting , or if its something wrong with keeping up with the values can someone tell me where exactly , referring to my code trial why it resulted in this answer .

package sorting;
public class soring {
    public static void selectionsort(int [] a ) {
        for (int i = 0; i < a.length - 1; i++) {
            int minindex = i; 
            int min = a[minindex];
            for(int j=i+1; j<a.length; j++) {
                if(min>a[j]) 
                    min = a[j];
                minindex = j;
            }
            a[minindex]=a[i];
            a[i]=min;
        }
    }

    public static void display (int []a) {
        for (int i =0 ; i<a.length-1 ;i++) {
            System.out.println(a[i]);
        }
    }

    public static void main(String[] args) {
        int [] a = {8,3,5,9,2};
        soring.selectionsort(a);
        soring.display(a);
    }
}

Solution

  • First problem:

    for (int i =0 ; i<a.length-1 ;i++) {
       System.out.println(a[i]);
    }
    

    In your display() method you're looping until less that the length minus one, which will not display the last value. Change this to i<a.length

    And again in your selectionsort() method you loop so that the last element is never touched. Second, you are missing brackets around one of your if statements. This is making it so that the line minindex = j; is not inside the if block and is therefore always executed. Change:

    if(min>a[j]) 
       min = a[j];
       minindex = j ;
    

    To:

    if(min>a[j]) {
         min = a[j];
         minindex = j ;
     }