Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

How to Implement Selection Sort in C?

Updated on 30 June, 2023

6.12K+ views
10 min read

Searching and sorting have always been pain points in computing, needing consistent improvements to tackle concerns. Regardless, its importance in computational processes is imperative to deal with data sorting and arrangement. 

In simple terms, sorting algorithms work to sort a sequence of elements. These elements could be numbers, characters, or anything – but the purpose is to sort the list in order quickly. Take the following example: We have the input as an array of numbers – [2, 6, 4, 3, 9, 1]. A sorting algorithm can transform this input array into this sorted array – [1, 2, 3, 4, 6, 9]. The sorting algorithm should also work with characters and sort them based on ASCII values. 

Check out our free courses to get an edge over the competition.

As easy as the task seems for humans, computers use several sorting algorithms designed over the decades to accomplish this task. Some of the most famous sorting algorithms include: 

  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Merge Sort
  • Quicksort
  • Counting Sort
  • Radix Sort
  • Bucket Sort
  • Heap Sort
  • Shell Sort

These algorithms differ in execution, which results in a huge difference in time and space complexities. Each of these algorithms has different use cases, and it is something that you must explore. Though, this article specifically explores one sorting algorithm- the Selection Sort.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Let’s begin our understanding of Selection Sorting in C by understanding its algorithm before diving into its code implementation using the C programming language. 

Selection sort algorithm – for sorting in ascending order

A straightforward and intuitive sorting algorithm called selection sort divides the input list into two sections: the sorted and the unsorted. It repeatedly chooses the smallest or largest element from the unsorted portion and swaps it with the element in the proper position in the sorted portion. The list is sorted until the end.

One of the key advantages of the selection sort program in C is its simplicity. The algorithm is easy to understand and implement, making it a popular choice for educational purposes and small datasets. Additionally, selection sort is an in-place sorting algorithm that operates directly on the input array without requiring extra memory space for auxiliary data structures. This characteristic can be advantageous in situations where memory is limited.

In all cases, the algorithm’s time complexity is given as O(n^2). This quadratic time complexity makes selection sort inefficient for large datasets, as the number of comparisons and swaps increases exponentially with the input size. Consequently, selection sort is generally not recommended for large-scale sorting tasks when more efficient algorithms, such as merge sort or quicksort, are available.

Follow these steps to implement selection sorting in C on a sequence of numbers, to arrange them in ascending order. 

  • Start by finding the minimum element in the array. Swap that element with the element present in the first position. 
  • Now, in the remaining array, from the second element onwards, find the minimum element again, and swap it with the element in the second position. This gives us the first two elements in the correct position.
  • Repeat this process n-1 times till the array ends to get the final sorted array in ascending order. 

If you have ever played a game of cards, these are precisely the steps you follow to sort your cards in place. Find the smallest card, put it in the first position, then from the remaining cards, find the smallest card again, put it in the second position, and so on. Naturally, this comes instinctively to us and is easier to do, but this is a precise sorting algorithm at its core! 

A selection sort example in C also exhibits poor performance characteristics when the input array is already partially sorted or contains repeated elements. Regardless of the initial order, a selection sort example in C always performs the same number of comparisons and swaps. This lack of adaptability contributes to its inefficiency compared to other sorting algorithms, which can exploit existing orders or other patterns to improve performance.

Despite its limitations, selection sort does have practical use cases. It can be beneficial when sorting small datasets or when simplicity and ease of implementation are prioritized over efficiency. Selection sort’s deterministic nature makes it a stable sorting algorithm, meaning it preserves the relative order of elements with equal values. This stability can be advantageous in certain scenarios where maintaining the original order is important.

Let’s look at how we can implement Selection Sort in C++ or C using a sample program. 

Check out upGrad’s Advanced Certification in DevOps 

Implementation of Selection Sort in C++ or C

#include <stdio.h>
int main()
{
  int array[100], n, c, d, position, t;
  printf("Enter the number of elements\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
  for (c = 0; c < (n - 1); c++) // finding minimum element (n-1) times
  {
    position = c;
    for (d = c + 1; d < n; d++)
    {
      if (array[position] > array[d])
        position = d;
    }
    if (position != c)
    {
      t = array[c];
      array[c] = array[position];
      array[position] = t;
    }
  }
  printf("Sorted list in ascending order:\n");
  for (c = 0; c < n; c++)
    printf("%d\n", array[c]);
  return 0;
}

Check out upGrad’s Advanced Certification in Blockchain Technology 

If you compile and run this C program, you will receive the following output:

>Enter the number of elements
5
>Enter 5 integers
5, 3, 2, 7, 1
>Sorted list in ascending order: 
1, 2, 3, 5, 7

The above program returns you the sorted list of input numbers in ascending form, and the algorithm used to achieve this output is the Selection Sort algorithm. 

While it should be intuitive how Selection Sort works, let’s take an example and try to dry run the Selection Sort algorithm and code to dissect how it works in real-time. 

Algorithmic Steps of Selection Sort:

  1. Start with the first element as the current minimum.
  2. Compare the current minimum with the next element in the unsorted part of the array.
  3. If a smaller element is found, update the current minimum.
  4. Continue comparing the current minimum with the remaining unsorted elements.
  5. Swap the current minimum with the first element of the unsorted portion.
  6. Keep repeating the steps 1-5 until the whole array is sorted.

Consider this:

```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
  int i, j, minIndex, temp;
  for (i = 0; i < n - 1; i++) {
    minIndex = i;
    for (j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    // Interchange the minimum element with the first element of the unsorted portion
    if (minIndex != i) {
      temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
}
int main() {
  int arr[] = {64, 25, 12, 22, 11};
  int n = sizeof(arr) / sizeof(arr[0]);
  selectionSort(arr, n);
  printf("Sorted array: \n");
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  return 0;
}
```

In this implementation, the `selectionSort` function takes an array `arr` and its size `n` as input. It iterates through the array and finds the minimum element in the unsorted portion for each iteration. If a smaller element is found, it updates the `minIndex`. After each iteration, it swaps the minimum element with the first element of the unsorted portion.

Understanding the working of Selection Sort

To understand how Selection Sort works, let’s take an unsorted array of integers and follow along with the algorithms. Here are our numbers: 

12, 29, 25, 8, 32, 17, 40. 

Scan the entire list sequentially and find the minimum element from the entire array. Here, 8 is found to be the minimum element. So, 8 will be sent to the 0th index (first position), and the element at the 0th index will be sent to the previous index of 8 (note that the items in bold are those that have been swapped): 

8, 29, 25, 12, 32, 17, 40. 

For the second position, where we currently have 29, we will again scan the list from the second element to the last element and find the smallest element there. We find that 12 is the smallest element now. So, we swap 12, and the element currently presents in the second position, i.e., 29. Here is what you get: 

8, 12, 25, 29, 32, 17, 40. 

We now have the first two elements of our array in their right place – sorted properly. 

This process is repeated for all the indexes until a sorted array is achieved. The entire working process looks like this: 

What we finally receive at the end is a completely sorted array in ascending order. But how efficient is this algorithm? How does it stand with other sorting algorithms? 

The efficiency of algorithms is measured using space and time complexity. Let’s understand the efficiency of our Selection Sort algorithm on both of these fronts.

Running complexity of Selection Sort

Let’s look at both the time and space complexity of Selection Sort. We’ll check out the complexity in all three cases – best, worst, and average, in order to get a complete picture.

1. Time complexity

Case Time Complexity
Best Case O(n2)
Average Case O(n2)
Worst Case O(n2)
  • Best Case Complexity occurs when the input array is already sorted, so the algorithm doesn’t need to perform any sorting. Even in that case, our Selection Sort algorithm will need to check all the elements again to ensure they’re in their right places to bring best-case complexity to O(n2).
  • Average Case Complexity is when the input array elements are presented in a jumbled order, a mix of ascending and descending orders. In that case, too, the time complexity is O(n2).
  • Worst Case Complexity is when the input array is in descending order and needs to be reversed entirely to bring it to the required sorted order. In this case, too, the complexity O(n2).

The complexity of our Selection Sort algorithm is O(n2) in all three cases. The reason for this is the algorithm runs through all the elements to check their correct position, regardless of the state of the input array. O(n2) is not a good time complexity for an algorithm, making Selection Sort slower, especially when compared to other sorting algorithms like Heap Sort and Merge Sort. 

2. Space Complexity

Space Complexity O(1)
Stable YES

The space complexity of the Selection Sort is O(1), which means our algorithm does not require additional memory space to perform computation. All of the comparisons and swapping happen in the original input array itself. This also makes this approach a stable sort.

In Conclusion

The world of sorting and searching is truly fascinating and full of new things to learn and explore. Selection Sort is just the beginning of it. If you understood Selection Sort and have implemented it successfully, your goal should be to dive deeper into different sorting techniques and try to analyze them yourself. That is how you will become a better programmer and, eventually, a better software developer. 

Software development, after all, is all about knowing the right set of tools, having the correct knowledge, and persevering with it. At upGrad, we understand the essence of software development and impart the same to our learners. Our courses are designed for students from varied backgrounds and often demand no strict prerequisite. One such course is the Full Stack Development Certificate Program

This fully online course, lasting nine months, requires no coding experience and helps you build your career in full-stack development. The course starts on 30th June, so get yourself registered soon!

Frequently Asked Questions (FAQs)

1. Is Selection Sort a favorable sorting method?

Selection Sort does not fare well in time complexity, so it isn’t a highly recommended sorting approach.

2. What is the time complexity of Selection Sort?

Selection Sort operates with the time complexity of O(n^2) in all three - best, worst, average - cases.

3. Is Selection Sort stable?

Yes, the Selection Sort is stable.

RELATED PROGRAMS