Click here to Skip to main content
15,885,910 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here's is my home work ,I want to know how much compares and exchanges takes place in selection sort.when i declared my array in reverse or in descending order like this

C#
int arr[]={5,4,3,2,1};

it's running fine and count compares and exchanges too but when i try to give 'n' and filled array in reverse order ,It filled it in descending order but it didn't work properly to sort in descending order to count my exchanges although it count compares. Here's is the code

    <pre lang="java"> public class SelectionSort {
        
            /**
             * @param args the command line arguments
             */
            public static void main(String[] args) {
                // TODO code application logic here
        
                Scanner in = new Scanner(System.in);
                int compares=0,exchanges=0,x;
                x=in.nextInt();
                 int []arr= new int [x];
                int n = arr.length;
                 int s=0;
                int min;
                int temp,i,j;
                System.out.print("Filling Array");
                for(i=n-1;i>0;i--)
                {
                    arr[i]=i;
                    System.out.print(" "+arr[i]);
                }
                System.out.println("");
                for(i=0 ; i < n ;i++)
                {
                    min = i ;
        
                    for(j=i+1;j<n ;j++)
                    {
                        compares++;
                        if(arr[min] > arr[j])
                            min=j;
        
                    }
                        if(min!=i)
                    {
                       exchanges++;
                        temp=arr[i];
                        arr[i]=arr[min];
                        arr[min]=temp;
                    }
        
                       System.out.println("Iteration " + ( ++s) );
                         for(int a=0;a<arr.length;a++)
                            System.out.print(" "+arr[a]);
        
                             System.out.println("");
                }
                System.out.println("");
                         System.out.println("Compares -- >> "+compares);
                        System.out.println("Exchanges -->> "+exchanges);
            }
        
        
        }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900