×

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

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

3 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 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.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time...

4 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

5 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.