1

I am trying to implement selection sort algorithm. But i see that it is failing for some cases. I take two different arrays and get two different result. Case 1: Integer [] arr= {100,90,6,43,12,1}; Result:{1,6,12,43,90,100}

Case 2: Integer [] arr= {100,90,6,43,12,7}; Result:{7,6,12,43,90,100}

Below is my code.

public class SelectionSort  {
    
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w)<0;
    }
    
    private static void exch(Comparable[] a,int i,int j) {
        Comparable swap=a[i];
        a[i]=a[j];
        a[j]=swap;
    }

    public static void sort(Comparable[] a) {

        int N= a.length;
        for(int i=0;i<N;i++) {
            int min=i;
            for(int j=i+1;j<N;j++) {
                if(less(a[j],a[min])) 
                    min=j;
                exch(a,i,min);

            }

        }
        
    }
    
}
   

2 Answers 2

1

change the algorithm like the following, it works fine

int N= a.length;
for(int i=0;i<N-1;i++) {
     int min=i;

     for(int j=i+1;j<N;j++) 
         if(less(a[j],a[min])) 
           min=j;
            
     exch(a,i,min);            
}
Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure that you want the exch to happen inside the j loop?

1 Comment

hey, thanks for pointing this out. I kept it outside the loop and it then worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.