×

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list.

Algorithm of Selection Sorting

In order to sort an array of n elements in increasing order, use the following commands:


selectionSort(array, size)
  repeat (size - 1) times
  set the first unsorted element as the minimum
  for each of the unsorted elements
    if element < currentMinimum
      set element as new minimum
  swap minimum with first unsorted position
end selectionSort


How Selection Sort Works?

Assume we're attempting to organise the components ascending.

  • Consider the first element the smallest.
Quick Sort
  • Compare the first and second elements. If the next element is less than the minimum, it should be the minimum.   Compare the third element to the minimum. If the third element is lesser, assign the minimum value to it; otherwise, do nothing. The process continues until the final element is added.
Quick Sort
  • Minimum is moved to the front of the unsorted list after each iteration.
Quick Sort
  • Indexing begins with the first unsorted element in each iteration. Steps 1–3 are repeated until all of the elements are in their proper places.
Quick Sort
Quick Sort
Quick Sort
Quick Sort

Code for Selection Sort in C

// Selection sort in C


#include <stdio.h>


// function to swap the the position of two elements
void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}


void selectionSort(int array[], int size) {
  for (int step = 0; step < size - 1; step++) {
    int min_idx = step;
    for (int i = step + 1; i < size; i++) {


      // To sort in descending order, change > to < in this line.
      // Select the minimum element in each loop.
      if (array[i] < array[min_idx])
        min_idx = i;
    }


    // put min at the correct position
    swap(&array[min_idx], &array[step]);
  }
}


// function to print an array
void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]);
  }
  printf("\n");
}


// driver code
int main() {
  int data[] = {20, 12, 10, 15, 2};
  int size = sizeof(data) / sizeof(data[0]);
  selectionSort(data, size);
  printf("Sorted array in Acsending Order:\n");
  printArray(data, size);
}


The following output should be generated by this programme:

Output


Array Sorted in Ascending Order:
-12 -9 0 17 46

Complexity for Selection Sort

Time Complexity
Best CaseO(n2)
Worst CaseO(n2)
AverageO(n2)
Space ComplexityO(1)
StabilityNo

Detail-oriented complexity

The nearby components are compared in Selection Sort.

CycleNumber of comparisons
1st( n-1 )
2nd( n-2 )
3rd( n-3 )
Last1

As a result, the number of iterations is:

( n-1 ) + ( n-2 ) + ( n-3 ) + ..... + 1 = n ( n-1 ) / 2

That almost equals n2

As a result, Complexity: O (n2)

Also, as we can see from the code, Selection sort necessitates two loops. As a result, the complexity is n*n = n2.

Complexities of Time

  • Complexity in the worst-case scenario: O (n2)
    • The worst case scenario happens if we wish to sort in ascending order but the array is in descending order.
  • Complexity in the Best-Case Scenario: O (n)
    • When the array has already been sorted, the outer loop repeats n times, but the inner loop does not. As a result, there are only n possible comparisons. As a result, complexity follows a linear pattern.
  • Case Complexity on the Average: O (n2)
    • When the items of an array are jumbled together, this happens (neither ascending nor descending).

The selection sort's time complexity is the same in all cases. At each step, you must identify the bare minimum and place it in the appropriate location. The minimum element is unknown until the array's end has not been reached.

Complexity of Space

  • Because an additional variable is utilised for swapping, the space complexity is O(1).

Applications for Selection Sorting

When using the selection sort,

  • Sorting a small list is considered necessary.
  • The cost of swapping is irrelevant.
  • It is necessary to check all of the elements.
  • In flash memory, the cost of writing to memory matters (number of writes/swaps is O(n) versus O(n2) for bubble sort).

Related Topics

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Advantages and Disadvantages of Linked List

Advantages of Linked List The linked list is a dynamic data structure.You can also decrease and increase the linked list at run-time. That is, you can allocate and deallocate memory at...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Binary Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.