Question

I'm having a problem for my output in this Selection Sort.

Here's the code:

public class SelectionSort{
    public static void main(String args[]){

        int [] arr_sort = {1, 7, 2, 18, 23, 13};

        System.out.println("Selection Sort");
        System.out.print("Before sorting: ");
        int x;
        for(x=0; x<arr_sort.length; x++){
            System.out.print(arr_sort[x] + " ");
        }

        System.out.println("");
        System.out.print("After sorting: ");

        int n = arr_sort.length;
        int i,j, min, temp;
        for(i=0; i<n; i++){
            min=1;
        for(j=i+1; j<n; j++){
         if (arr_sort[j]<arr_sort[min]){
            min=j;
            temp=arr_sort[i];
            arr_sort[i]=arr_sort[min];
            arr_sort[min]=temp;
        }

    }

System.out.print(arr_sort[i] + " ");
 }

}

}

Output:

Selection Sort
Before sorting: 1 7 2 18 23 13 
After sorting: 2 1 7 18 23 13 
Était-ce utile?

La solution

The fact that min is declared outside the loop is the problem.

When starting a new iteration, it will still retain the old value, so you'll be comparing with an element already found to be the minimum and selected.

Also, min shouldn't be 1, make it i instead, as you don't want to be comparing with the second element at each step.

After these changes it works, but it's not really selection sort, you need to find the minimum and only swap then, not each time you find a smaller element.

On to the code:

int n = arr_sort.length;
int i, j, temp; // min removed here
for (i = 0; i < n; i++)
{
  int min = i; // min declared here and changed to i
  for (j = i + 1; j < n; j++)
  {
     if (arr_sort[j] < arr_sort[min])
     {
        min = j;
     }
  }
  // moved swap to here
  temp = arr_sort[i];
  arr_sort[i] = arr_sort[min];
  arr_sort[min] = temp;
  System.out.print(arr_sort[i] + " ");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top