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
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
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

Selection Sort Algorithm in Data Structure: Code, Function & Example

Updated on 18 August, 2023

8K+ views
8 min read

What Is a Selection Sort Algorithm in Data Structure?

The selection sort algorithm is a simple sorting technique for organising a list of components in ascending or descending order. It is a comparison-based sorting algorithm that compares list components to determine their relative rank.

The selection sort algorithm works by dividing the input list into two parts: the sorted component and the unsorted component. The sorted section is initially empty, and the unsorted part contains the complete list. The method identifies the smallest (or largest, depending on the sorting order) element from the unsorted section and pushes it to the end of the sorted part every time. This step is repeated until the full list has been sorted.

Selection Sort is inefficient for large lists, with an average and worst case time complexity of O(n2). This implies that the time required to sort the list grows quadratically as the number of elements increases. It does, however, have the virtue of being simple to grasp and simple to implement.

Before strengthening advanced algorithms with upGrad’s Executive PG Program in Machine Learning & AI from IIITB, let us take you through the basics of the selection sort algorithm!

How Does the Selection Sort Algorithm Work?

The Selection Sort technique identifies the least (or greatest) element in the list’s unsorted section and places it at the end of the sorted section. This process is repeated until the full list has been sorted. The following is a detailed explanation of how the selection sort algorithm works:

Consider using Selection Sort to sort a collection of numbers in ascending order:

Input: [44, 89, 52, 12, 29, 10, 80]

Step 1:

  • At first, the entire list is unsorted.
  • We pick the smallest element (10) in the unsorted part of the list and swap it with the first element (44).
  • The sorted half now has only one element (10), whereas the unsorted part has one less element.
  • Following Step 1, the following list: [10, 89, 52, 12, 29, 44, 80]

Step 2:

  • The minimum element from the remaining unsorted component (12) is found and exchanged with the unsorted part’s second element (89).
  • The sorted part now has two components (10, 12), and the unsorted half has one less element.
  • Following Step 2, the following list: [10, 12, 52, 89, 29, 44, 80]

Step 3:

  • The minimal element from the remaining unsorted component (29) is found and exchanged with the unsorted part’s third element (52).
  • The sorted part now has three elements (10, 12, 29), and the unsorted half has one less element.
  • Following Step 3, the following list: [10, 12, 29, 89, 52, 44, 80]

Step 4:

  • The minimum element from the remaining unsorted component (44) is found and exchanged with the unsorted part’s fourth element (89).
  • The sorted part now has four elements (10, 12, 29, 44), whereas the unsorted part has one less element.
  • Following Step 4, the following list: [10, 12, 29, 44, 52, 89, 80]

Step 5:

  • The minimum element from the remaining unsorted part (52) is found and exchanged with the unsorted part’s fifth element (52).
  • The sorted part now has five elements (10, 12, 29, 44, 52), whereas the unsorted part has one less element.
  • Following Step 5, the following list: [10, 12, 29, 44, 52, 89, 80]

Step 6:

  • The minimum element from the remaining unsorted part (80) is found and exchanged with the unsorted part’s sixth element (89).
  • The sorted half now has six elements (10, 12, 29, 44, 52, 89), whereas the unsorted part has one less element.
  • Following Step 6, the following list: [10, 12, 29, 44, 52, 80, 89]

Step 7:

  • The entire list has been sorted, as there are no more elements in the unsorted section.
  • [10, 12, 29, 44, 52, 80, 89] is the final sorted list.

Here’s a detailed description of  selection sort in python:

def selection_sort(array):
    m = len(array)
    for i in range(m - 1):
        # Assume the current index (i) has the minimum value
        min_index = i
        # Find the minimum element in the remaining unsorted part
        for j in range(i + 1, m):
            if array[j] < array[min_index]:
                min_index = j
        # Swap the found minimum element with the first element of the unsorted part
        array[i], array[min_index] = array[min_index], array[i]

selection sort example usage:

my_list = [68, 34, 28, 19, 22, 10, 50]
selection_sort(my_list)
print(my_list)  

Output: [10, 19, 22, 28, 34, 50, 68]

Enroll for the Machine Learning Course from the World’s top Universities. Earn Masters, Executive PGP, or Advanced Certificate Programs to fast-track your career.

Algorithm and Pseudocode of a Selection Sort Algorithm

The following is the selection sort algorithm:

  • Begin with the smallest (or largest, depending on the sorting order) element.
  • In the unsorted segment, compare the minimum element to the following element.
  • If a smaller (or larger) element is discovered, the index of the minimum (or maximum) element is updated.
  • Continue comparing and updating the minimum (or maximum) element until the unsorted segment is finished.
  • Swap the identified minimum (or maximum) element with the unsorted part’s initial element.
  • Move the sorted part’s boundary one element to the right to expand it.
  • Steps 2-6 should be repeated until the full list is sorted.

The pseudocode of a Selection Sort Algorithm is as follows:

function selection_sort(array):
    m = length(array)
    for i = 0 to m-2:
        # Assume the current index (i) has the minimum value
        min_index = i
        # Find the minimum element in the remaining unsorted part
        for j = i + 1 to m-1:
            if array[j] < array[min_index]:
                min_index = j
        # Swap the found minimum element with the first element of the unsorted part
        swap(array[i], array[min_index])

selection sort example usage:

my_list = [69, 49, 25, 19, 20, 11, 28]
selection_sort(my_list)
print(my_list) 

Output: [11, 19, 20, 25, 28, 49, 69]

Check out upGrad’s free courses on AI.

The Complexity of Selection Sort Algorithm

The selection sort algorithm’s complexity can be measured in terms of time and space complexity:

Time Complexity: Selection Sort has an O(N2) time complexity due to the two nested loops:

  • One loop to select an array element one by one = O(N)
  • Another loop to compare that element to every other element in the array = O(N)
  • As a result, total complexity = O(N) * O(N) = O(N*N) = O(N2)

Space Complexity: Since the selection sort algorithm sorts in place, no additional memory is required for temporary data structures. As a result, Selection Sort’s space complexity is O(1), showing that the space needed by the method is constant and does not depend on the input list’s size.

Applications of Selection Sort Algorithm

Despite its slightly dull performance in comparison to more efficient sorting algorithms, the selection sort algorithm has several useful applications as follows:

  • Bubble sort is routinely outperformed by selection sort.
  • When memory writes are expensive or constrained (for example, in embedded systems with limited resources), the swapping process of Selection Sort can be useful. It uses fewer swaps than other sorting algorithms, such as Bubble Sort.
  • Selection sort is preferable to insertion sort in terms of the number of writes ((n) swaps versus O(n2) swaps).
  • It almost always outnumbers the number of writes produced by cycle sort, despite the fact that cycle sort is theoretically best in terms of write count.
  • Selection Sort is parallelisable because each iteration of the outer loop can be done individually. This characteristic may be useful in some parallel computing scenarios.

Example of Selection Sort Algorithm 

The following is the selection sort program:

#include <stdio.h>
void selection_sort(int array[], int k) {
    for (int l = 0; l < k - 1; l++) {
        int min_index = l;
        for (int m = l + 1; m < k; m++) {
            if (array[m] < array[min_index]) {
                min_index = m;
            }
        }
        int temp = array[l];
        array[l] = array[min_index];
        array[min_index] = temp;
    }
}
int main() {
    int my_list[] = {46, 74, 52, 32, 21, 13, 80};
    int k = sizeof(my_list) / sizeof(my_list[0]);
    selection_sort(my_list, k);
    printf("Sorted list: ");
    for (int l = 0; l < k; l++) {
        printf("%d ", my_list[l]);
    }
    printf("\n");
    return 0;
}

In the given selection sort code, we first implement the selection_sort function, which accepts as input an integer array of size k. The selection sort algorithm is used to sort the array in ascending order.

The main function creates a test array called my_list, sorts it using the selection_sort function, and then prints the sorted list.

When you execute the programme, it will produce the following output:

Sorted list: 13 21 32 46 52 74 80

Conclusion

The selection sort algorithm is a simple and intuitive sorting strategy that may be used in educational settings and scenarios with limited resources. Although its O(n2) time complexity makes it unsuitable for huge datasets, its basic code implementation makes it useful for teaching sorting ideas. While not appropriate for high-performance applications, Selection Sort is useful when partial sorting or parallelisation is required.

Strengthening yourself with the right courses and a collection of well-equipped equipment is set to benefit your profession in the long term. upGrad’s Executive Post Graduate Programme in Software Development – Specialisation in Full Stack Development is one such course to prepare for the growing tech world. If you want to be a full-stack developer, this programme will help you develop your front-end and back-end programming skills. 

Frequently Asked Questions (FAQs)

1. How does selection sort work in the context of data structures?

Selection sort is a straightforward sorting algorithm that selects the smallest element in the unsorted half of the array and swaps it with the first unsorted member. This is repeated until the array has been sorted.

2. How can I write a selection sort program in a programming language like Python?

In Python, you can create a selection sort programme by writing a function that accepts an array as input and sorts it in place.

3. What are the key steps involved in the selection sort algorithm?

The following are the key steps in the selection sort algorithm: Determine the smallest (or greatest) element. Replace the discovered element with the first unsorted element. In the unsorted section, look for the actual minimum (or maximum) element. Repeat the procedure until the array has been sorted.

4. Why do we use a selection sort algorithm?

Selection sort is used for the following purposes: Simplicity in implementation and comprehension. Sorting in place with minimal extra memory. Small datasets where reasonable performance is required. It performs best with partially sorted arrays.