Answer:
#include <iostream>
#include<time.h>
using namespace std;
void sort(int a[20],int n) //selection sort
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++) //finds minimum element
{
if(a[i]>a[j]) //swaps minimum element to its right place
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int main()
{
srand(time(NULL));
int arr[20],n=20,i;
for(i=0;i<n;i++)
arr[i]=rand() % 100 + 1; //assigns random number to each array element
cout<<"Before sorting\n";
for(i=0;i<n;i++)
cout<<arr[i]<<" "; //prints array before calling sort func
sort(arr,20); //sort the passed array
cout<<"\nAfter sorting\n";
for(i=0;i<n;i++)
cout<<arr[i]<<" "; //prints array after sorting
return 0;
}
OUTPUT :
Please find the attachment below.
Explanation:
The program above first assigns random number from 1 to 100 to each element of array using rand(). srand(time(NULL)) is used to generate new number every time otherwise same random number will be produced at a time. Then sorting method is called in which selection sort algorithm is used.
Selection sort algorithm finds the minimum element in each pass and place it into its right position. For example - 34,54,12,5 is passed
After Pass 1 - 5 54 12 34
After Pass 2 - 5 12 54 34
After Pass 3 - 5 12 34 54