Sidharth sharma
Sidharth sharma

Reputation: 3

why my selection sort program is not working?

public class first {
    public static void main(String args[]){
        int arr[]={5,4,1,3,2};

        for(int i=0; i<arr.length-1;i++){
            int smallest=arr[i];                     
            for(int j=i+1; j<arr.length;j++){
                if(smallest>arr[j]){
                    smallest=arr[j];
                }
            }
            //swap
            int temp=smallest;
            smallest=arr[i];
            arr[i]=temp;
        }
        
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}

i have done this problem by getting the smallest in terms of index number and the program works properly . but when i am taking smallest in terms of number present at index number , this program did not work.your text

Upvotes: 0

Views: 28

Answers (1)

Anon
Anon

Reputation: 384

you need to save the smallest number index not the number it self so you know the positions to make the swap

    for (int i = 0; i < arr.length - 1; i++) {
        int indexOfSmallestNum = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[indexOfSmallestNum] > arr[j]) indexOfSmallestNum = j;
        }
        int temp = arr[i];
        arr[i] = arr[indexOfSmallestNum];
        arr[indexOfSmallestNum] = temp;
    }

Upvotes: 0

Related Questions