SELECTION SORT

Introduction

Selection sort is an in-place sorting algorithm. In every iteration, we find the minimum value and swap it with the current index. That is to say that we start looping with index i and loop again from i+1 till the end, find the min value and swap it with the element at index i.

This algorithm falls under Brute Force Technique which is a straight forward approach to solve a problem. Let's look at the working of this algorithm.

Working Procedure

Do refer the code available the end of this section to understand the following theory.

  1. Consider an array of n elements.
  2. Loop the array from i = 0 to n-2(Outer loop).
  3. Assign min = i.
  4. Loop the array from j = 0 to n-i-1(Inner loop).
  5. Assign min = j if a[j] < a[min].
  6. After the inner loop ends, if min != i then swap a[i] & a[min]. (It means that if we found the index of minimum value among the elements i+1 to n-1 then swap it with the current element i.e i).
  7. After the outer loop ends, we get the required sorted array.

Time Complexity

PS: We give random inputs because the no. of input will generally be 100 or 1000 to find the time complexity and manually giving so many inputs is cumbersome work.

The basic operation in this algorithm is the comparision between current element and the next element(step 5 in the above working procedure). So increment the count variable above this if condition to get the count of no. of times the basic operation has been performed.

Selection Sort

Time Complexity: O(n2)

Similar posts: Bubble Sort

Code file

Please open this in your pc or with a compatible app in your mobile.

C++ Implementation for SELECTION SORT

That's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!

Copyright © NStF Blogs 2021