C Programming Tutorial

Advertisements

Write a program to sort an array using Selection sort in C++



       #include<iostream.h>
       #include<conio.h>
       void main()
       {
              int arr[10],i,j,temp,small,pos;
              clrscr();

              for(i=0;i<10;i++)
              {
                 cout<<"Enter any number : "; 
                 cin>>arr[i]; 
              }
              
              cout<<"\n\tUnsorted array : ";
              for(i=0;i<size;i++)
              cout<<arr[i]<<", ";
              
              for(j=0;j<10;j++)	
              {
		              small = arr[j];
		              pos=j;
	
		              for(i=j;i<10;i++)
		              {
			                 if(small>=arr[i])
			                 {
				                     small=arr[i];
				                     pos=i;
			                 }				
		              }

		              temp = arr[j];
		              arr[j]=small;
		              arr[pos]=temp;
              }

              cout<<"\n\tSorted   array : ";
              for(i=0;i<size;i++)
              cout<<arr[i]<<", ";

              getch();
}

   Output : 

              Enter any number : 78
              Enter any number : 45
              Enter any number : 12
              Enter any number : 89
              Enter any number : 56
              Enter any number : 23
              Enter any number : 79
              Enter any number : 46
              Enter any number : 13
              Enter any number : 82
              
              Unsorted array : 78, 45, 12, 89, 56, 23, 79, 46, 13, 82,
              Sorted   array : 12, 13, 23, 45, 46, 56, 78, 79, 82, 89,




Advertisement