Google Add

Search

Selection Sort Program in C , C++ - Sorting Algorithm

Write a C, C++ program to implement selection sort algorithm. Given an unsorted array, we have to write a code to sort an array using selection sort algorithm. What's the time complexity of selection sort.

Selection Sort

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



Like Bubble Sort, Selection Sort is also good for small data set. For sorting large set of elements use Quick Sort or Merge Sort.

Sorting Algorithms and their time complexity

Complexity of Selection Sort

The time complexity of selection sort is  O(n^2). Similar to Bubble Sort.





Selection Sort Program and it's example





Selection Sort Program in C


#include <stdio.h> 

void main() {

    int arr[100], min, i, j, temp, n;

    printf("Enter the size of an array (Max 100)\n ");
    scanf("%d", &n);

    printf("Enter an array values\n");

   /* Input array elements */

    for(i = 0; i < n; i++)
       scanf("%d", &arr[i]);

    /* Selection Sort implementation logic. */

    for(i = 0; i < n-1; i++) {
     
       min = i;
     
       for(j = i+1; j < n; j++){          

         if(arr[j] < arr[min]){

              min = j;
           }
      }
      
      temp     = arr[min];
      arr[min] = arr[i];
      arr[i]   = temp;
   }
  
  

   printf("After sorting an array is: \n");
   for(i = 0; i < n; i++)
       printf(" %d", arr[i]);

}


Selection Sort Program in C++


#include <iostream>
using namespace std;

int main() {
 
     int arr[100], min, i, j, temp, n;

    cout << " Enter the size of an array (Max 100)\n ";
    cin  >>  n;

    cout << "Enter an array values\n";

   /* Input array elements */

    for(i = 0; i < n; i++)
       cin >> arr[i];

    /* Selection Sort implementation logic. */

    for(i = 0; i < n-1; i++) {
     
       min = i;
     
       for(j = i+1; j < n; j++){          

         if(arr[j] < arr[min]){

              min = j;
           }
      }
      
      temp     = arr[min];
      arr[min] = arr[i];
      arr[i]   = temp;
   }
  
  

   cout << "After sorting an array is: \n";
   for(i = 0; i < n; i++)
       cout << arr[i] << "\n";
       
 return 0;
}

Output :

Enter the size of an array : 5

Enter an array values :

4
2
6
1
3

After sorting an array is :

1
2
3
4
6


No comments:

Post a Comment