How to Sort an Array using Selection Sort. What's the time complexity of selection sort and how to write it's code in C, C++.

###

Selection sort is good if your sorting small number of elements. As it's implementation is easy. For sorting large set of elements use Quick Sort or Merge Sort.

Sorting Algorithm

##

Similarly you can implement the same code logic in C++.

In this post i am going to describe what is selection sort, how it works and what's the complexity of selection sort.

###
**What is Selection Sort ?**

Selection sort is a in-place comparison technique . In selection sort we pick element and move the element to it's correct position. We repeat this process until all the elements are sorted.

Selection sort is good if your sorting small number of elements. As it's implementation is easy. For sorting large set of elements use Quick Sort or Merge Sort.

Sorting Algorithm

**Complexity of Selection Sort**

It has complexity of O(n^2). Similar to Bubble Sort.

##
**Selection Sort Program in C**

#include <stdio.h>void main(){ int n,i,j,temp,arr[100],index; printf("How many elements you want to enter "); scanf("%d",&n); printf("Enter elements\n"); /* Taking input from user. */ for(i=0;i<n;i++) scanf("%d",&arr[i]); /* Selection Sort implementation logic. */ for(i=0;i<n;i++){ index = i; for(j=i+1;j<n;j++){ if(arr[j]<arr[index]){ index = j; } } temp = arr[index]; arr[index] = arr[i]; arr[i] = temp; } printf("After sorting is: "); for(i=0;i<n;i++) printf(" %d",arr[i]); }

Similarly you can implement the same code logic in C++.

## No comments:

## Post a Comment