Selection Sort ( Array )
PROBLEM :
Given a random set of numbers, Print them in sorted order.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.
Constraints:
1 = T = 10
1 = N = 1000
1 =A[i]<100
Example:
Input:
1
2
3 1 4 5 2
Output:
1 2 3 4 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void SelectionSort(int [],int ) ;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
SelectionSort(arr,no) ;
for(int i=0;i<no;i++)
cout<<arr[i]<<" " ;
cout<<endl ;
}
return 0;
}
void SelectionSort(int arr[],int no)
{
int i,j,temp,currmin ;
for(i=0;i<no;i++)
{
currmin=i ;
for(j=i+1;j<no;j++)
{
if(arr[j]<arr[currmin])
currmin=j ;
}
if(i!=currmin)
{
temp=arr[i] ;
arr[i]=arr[currmin] ;
arr[currmin]=temp ;
}
}
}
--------------------------------------------------------------------------------
Given a random set of numbers, Print them in sorted order.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.
Constraints:
1 = T = 10
1 = N = 1000
1 =A[i]<100
Example:
Input:
1
2
3 1 4 5 2
Output:
1 2 3 4 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void SelectionSort(int [],int ) ;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
SelectionSort(arr,no) ;
for(int i=0;i<no;i++)
cout<<arr[i]<<" " ;
cout<<endl ;
}
return 0;
}
void SelectionSort(int arr[],int no)
{
int i,j,temp,currmin ;
for(i=0;i<no;i++)
{
currmin=i ;
for(j=i+1;j<no;j++)
{
if(arr[j]<arr[currmin])
currmin=j ;
}
if(i!=currmin)
{
temp=arr[i] ;
arr[i]=arr[currmin] ;
arr[currmin]=temp ;
}
}
}
--------------------------------------------------------------------------------
Comments
Post a Comment