# Selection sort

## Working of Selection sort#

In selection sort, the comparison will be between two numbers from the starting of an array. the lesser will be left and a greater number will be right in ascending order.swapping of numbers will be done between two numbers to get the ascending or descending order. the complete array elements are compared with every single element in an array from starting of an array. the first element and the second element is compared, If first is lesser than the second, it will remain as it is and first, is compared with third, and fourth by this we will get our first lowest element and, next the comparison starts from the second element with all other elements.

This comparison goes on. if there are n elements this comparison processes repeats n-1 times, because the last term will be the greatest one we cannot compare with other terms in ascending order. In the case of sorting in ascending order, the smallest element will be at first and in case of sorting in descending order, the largest element will be at first.) first, the comparison starts with the first element. the second comparison starts with the second element. the third comparison starts from third element.this comparison goes until it detects the greatest among all the elements

If the elements in the array are n .the process mentioned above should be repeated n-1times to get the required result. 1. zeroth index element is 9, now 9 is compared with the next element, next 9 is greater than 3, swapping of 9,3 takes place
2. zeroth index element is 3. this is compared with the second index element, 3 is smaller than 21, no swapping will be done
3. zeroth index element is 3,3 is compared to the 6,3 is smaller than 6, so swapping takes place
4. zeroth index element is 3,3 is compared with the 1, (3 > 1 )so the swapping takes place
5. the first iteration is over, for the next iteration comparison will be done from the first index element (9) to the last element

## The time complexity of selection sort#

• Worst Case Time Complexity [ Big-O ]: O(n2)
• Best Case Time Complexity [Big-omega]: O(n2)
• Space Complexity: O(1)

## Program for Selection sort#

#include<stdio.h>
int main()
{
int n,i,j,temp;
int arr;
printf("no of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the %dst element",i+1);
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
printf("In ascending order: ");
for(i=0;i<n;++i)
printf("%d ",arr[i]);
return 0;
}

Last updated on by vishal devxo