Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Selection Sort Algorithm

I have some questions about selection sort.I'm a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order 
        }
    }

Output is :

4
3
2
1
4
3
2
4
3
4

What's wrong ?

like image 453
snnlankrdsm Avatar asked Dec 21 '22 05:12

snnlankrdsm


2 Answers

selection sort is about finding the min value in each step of loop. you didn't find out the min value (by if statement maybe), just simply exchange the value in your inner loop. so you actually didn't do a sort.

correction based on your implementation:

final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
    int min;
    for (int i = 0; i < arr.length; i++) {
        // Assume first element is min
        min = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min = j;

            }
        }
        if (min != i) {
            final int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        System.out.println(arr[i]);// I print the in ascending order
    }

this should give you output:

1
2
3
4
5
like image 67
Kent Avatar answered Dec 24 '22 01:12

Kent


Correct:

public class Test {

public static void main(String args[]){
    int[] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;
        for(int j = i + 1;j<arr.length;j++)
        {
            if(arr[j] < arr[min]) { min = j;}
        }
        int temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
        System.out.println(arr[i]);//I print the in ascending order 
    }
}

}

About the min part: it just refers to the index of whatever is the current min. You move on down the array until you meet the new min, and set min to that index. So 5 is the minimum number [min =0] until you see 4 [so now min =1] but then you compare 3 to whatever is stored at 4 [when min=1] and then realize that you should set min=2.... etc. etc.

like image 24
varatis Avatar answered Dec 24 '22 00:12

varatis