 Open in App
Not now

# Difference between Insertion sort and Selection sort

• Difficulty Level : Medium
• Last Updated : 30 Mar, 2023

Insertion sort and selection sort are two popular sorting algorithms, and their main difference lies in how they select and place elements in a sorted sequence.

### Selection Sort:

1. In selection sort, the input array is divided into two parts: a sorted part and an unsorted part.
2. The algorithm repeatedly finds the minimum element in the unsorted part and swaps it with the leftmost element of the unsorted part, thus expanding the sorted part by one element.
3. Selection sort has a time complexity of O(n^2) in all cases.

### Insertion Sort:

1. In insertion sort, the input array is also divided into two parts: a sorted part and an unsorted part.
The algorithm picks up an element from the unsorted part and places it in the correct position in the sorted part, shifting the larger elements one position to the right.
Insertion sort has a time complexity of O(n^2) in the worst case, but can perform better on partially sorted arrays, with a best-case time complexity of O(n).
Main differences:
2. Selection sort scans the unsorted part to find the minimum element, while insertion sort scans the sorted part to find the correct position to place the element.
Selection sort requires fewer swaps than insertion sort, but more comparisons.
Insertion sort is more efficient than selection sort when the input array is partially sorted or almost sorted, while selection sort performs better when the array is highly unsorted.
In summary, both algorithms have a similar time complexity, but their selection and placement methods differ. The choice between them depends on the characteristics of the input data and the specific requirements of the problem at hand.

1. Simple and easy to understand and implement.
2. Efficient for small data sets or nearly sorted data.
3. In-place sorting algorithm, meaning it doesn’t require extra memory.
4. Stable sorting algorithm, meaning it maintains the relative order of equal elements in the input array.

1. Inefficient for large data sets or reverse-ordered data, with a worst-case time complexity of O(n^2).
2. Insertion sort has a lot of swaps, which can make it slow on modern computers.

1. Simple and easy to understand and implement.
2. Efficient for small data sets or nearly sorted data.
3. In-place sorting algorithm, meaning it doesn’t require extra memory.

1. Inefficient for large data sets, with a worst-case time complexity of O(n^2).
2. Selection sort has a lot of comparisons, which can make it slow on modern computers.
3. Unstable sorting algorithm, meaning it may not maintain the relative order of equal elements in the input array.

In this article, we will discuss the difference between the Insertion sort and the Selection sort:

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

Algorithm:
To sort an array of size n in ascending order:

• Iterate from arr to arr[n] over the array.
• Compare the current element (key) to its predecessor.
• If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

Below is the image to illustrate the Insertion Sort: Below is the program for the same:

## C++

 `// C++ program for the insertion sort``#include ``using` `namespace` `std;` `// Function to sort an array using``// insertion sort``void` `insertionSort(``int` `arr[], ``int` `n)``{``    ``int` `i, key, j;``    ``for` `(i = 1; i < n; i++) {``        ``key = arr[i];``        ``j = i - 1;` `        ``// Move elements of arr[0..i-1],``        ``// that are greater than key to``        ``// one position ahead of their``        ``// current position``        ``while` `(j >= 0 && arr[j] > key) {``            ``arr[j + 1] = arr[j];``            ``j = j - 1;``        ``}``        ``arr[j + 1] = key;``    ``}``}` `// Function to print an array of size N``void` `printArray(``int` `arr[], ``int` `n)``{``    ``int` `i;` `    ``// Print the array``    ``for` `(i = 0; i < n; i++) {``        ``cout << arr[i] << ``" "``;``    ``}``    ``cout << endl;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 12, 11, 13, 5, 6 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Function Call``    ``insertionSort(arr, N);``    ``printArray(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``class` `GFG``{``      ` `// Function to sort an array using``// insertion sort``static` `void` `insertionSort(``int` `arr[], ``int` `n)``{``    ``int` `i, key, j;``    ``for` `(i = ``1``; i < n; i++)``    ``{``        ``key = arr[i];``        ``j = i - ``1``;` `        ``// Move elements of arr[0..i-1],``        ``// that are greater than key to``        ``// one position ahead of their``        ``// current position``        ``while` `(j >= ``0` `&& arr[j] > key)``        ``{``            ``arr[j + ``1``] = arr[j];``            ``j = j - ``1``;``        ``}``        ``arr[j + ``1``] = key;``    ``}``}` `// Function to print an array of size N``static` `void` `printArray(``int` `arr[], ``int` `n)``{``    ``int` `i;` `    ``// Print the array``    ``for` `(i = ``0``; i < n; i++) {``        ``System.out.print(arr[i] + ``" "``);``    ``}``    ``System.out.println();``}``  ` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``12``, ``11``, ``13``, ``5``, ``6` `};``    ``int` `N = arr.length;` `    ``// Function Call``    ``insertionSort(arr, N);``    ``printArray(arr, N);``}``}` `// This code is contributed by code_hunt.`

## Python3

 `# Python 3 program for the insertion sort` `# Function to sort an array using``# insertion sort``def` `insertionSort(arr, n):``    ``i ``=` `0``    ``key ``=` `0``    ``j ``=` `0``    ``for` `i ``in` `range``(``1``,n,``1``):``        ``key ``=` `arr[i]``        ``j ``=` `i ``-` `1` `        ``# Move elements of arr[0..i-1],``        ``# that are greater than key to``        ``# one position ahead of their``        ``# current position``        ``while` `(j >``=` `0` `and` `arr[j] > key):``            ``arr[j ``+` `1``] ``=` `arr[j]``            ``j ``=` `j ``-` `1``        ``arr[j ``+` `1``] ``=` `key` `# Function to print an array of size N``def` `printArray(arr, n):``    ``i ``=` `0` `    ``# Print the array``    ``for` `i ``in` `range``(n):``        ``print``(arr[i],end ``=` `" "``)``    ``print``(``"\n"``,end ``=` `"")` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=`  `[``12``, ``11``, ``13``, ``5``, ``6``]``    ``N ``=`  `len``(arr)` `    ``# Function Call``    ``insertionSort(arr, N)``    ``printArray(arr, N)``    ` `    ``# This code is contributed by bgangwar59.`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG``{` `    ``// Function to sort an array using``    ``// insertion sort``    ``static` `void` `insertionSort(``int``[] arr, ``int` `n)``    ``{``        ``int` `i, key, j;``        ``for` `(i = 1; i < n; i++)``        ``{``            ``key = arr[i];``            ``j = i - 1;` `            ``// Move elements of arr[0..i-1],``            ``// that are greater than key to``            ``// one position ahead of their``            ``// current position``            ``while` `(j >= 0 && arr[j] > key)``            ``{``                ``arr[j + 1] = arr[j];``                ``j = j - 1;``            ``}``            ``arr[j + 1] = key;``        ``}``    ``}` `    ``// Function to print an array of size N``    ``static` `void` `printArray(``int``[] arr, ``int` `n)``    ``{``        ``int` `i;` `        ``// Print the array``        ``for` `(i = 0; i < n; i++)``        ``{``            ``Console.Write(arr[i] + ``" "``);``        ``}``        ``Console.WriteLine();``    ``}` `    ``// Driver code``    ``static` `public` `void` `Main()``    ``{``        ``int``[] arr = ``new` `int``[] { 12, 11, 13, 5, 6 };``        ``int` `N = arr.Length;` `        ``// Function Call``        ``insertionSort(arr, N);``        ``printArray(arr, N);``    ``}``}` `// This code is contributed by Dharanendra L V`

## Javascript

 ``

Output:

`5 6 11 12 13`

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

• The subarray is already sorted.
• The remaining subarray is unsorted.

In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

Below is an example to explains the above steps:

```arr[] = 64 25 12 22 11

// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64

// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64

// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64 ```

Below is the program for the same:

## C++

 `// C++ program for implementation of``// selection sort``#include ``using` `namespace` `std;` `// Function to swap two number``void` `swap(``int``* xp, ``int``* yp)``{``    ``int` `temp = *xp;``    ``*xp = *yp;``    ``*yp = temp;``}` `// Function to implement the selection``// sort``void` `selectionSort(``int` `arr[], ``int` `n)``{``    ``int` `i, j, min_idx;` `    ``// One by one move boundary of``    ``// unsorted subarray``    ``for` `(i = 0; i < n - 1; i++) {` `        ``// Find the minimum element``        ``// in unsorted array``        ``min_idx = i;``        ``for` `(j = i + 1; j < n; j++)``            ``if` `(arr[j] < arr[min_idx])``                ``min_idx = j;` `        ``// Swap the found minimum element``        ``// with the first element``        ``swap(&arr[min_idx], &arr[i]);``    ``}``}` `// Function to print an array``void` `printArray(``int` `arr[], ``int` `size)``{``    ``int` `i;` `    ``for` `(i = 0; i < size; i++) {``        ``cout << arr[i] << ``" "``;``    ``}``    ``cout << endl;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 64, 25, 12, 22, 11 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Function Call``    ``selectionSort(arr, n);``    ``cout << ``"Sorted array: \n"``;` `    ``// Print the array``    ``printArray(arr, n);``    ``return` `0;``}`

## Java

 `// Java program for implementation of``// selection sort``import` `java.util.*;``class` `GFG``{` `// Function to implement the selection``// sort``static` `void` `selectionSort(``int` `arr[], ``int` `n)``{``    ``int` `i, j, min_idx;` `    ``// One by one move boundary of``    ``// unsorted subarray``    ``for` `(i = ``0``; i < n - ``1``; i++)``    ``{` `        ``// Find the minimum element``        ``// in unsorted array``        ``min_idx = i;``        ``for` `(j = i + ``1``; j < n; j++)``            ``if` `(arr[j] < arr[min_idx])``                ``min_idx = j;` `        ``// Swap the found minimum element``        ``// with the first element``        ``int` `temp = arr[min_idx];``        ``arr[min_idx]= arr[i];``        ``arr[i] = temp;``    ``}``}` `// Function to print an array``static` `void` `printArray(``int` `arr[], ``int` `size)``{``    ``int` `i;` `    ``for` `(i = ``0``; i < size; i++) {``        ``System.out.print(arr[i]+ ``" "``);``    ``}``    ``System.out.println();``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``64``, ``25``, ``12``, ``22``, ``11` `};``    ``int` `n = arr.length;` `    ``// Function Call``    ``selectionSort(arr, n);``    ``System.out.print(``"Sorted array: \n"``);` `    ``// Print the array``    ``printArray(arr, n);``}``}` `// This code is contributed by aashish1995`

## Python3

 `# Python3 program for implementation of``# selection sort` `# Function to implement the selection``# sort``def` `selectionSort(arr, n):` `    ``# One by one move boundary of``    ``# unsorted subarray``    ``for` `i ``in` `range``(n ``-` `1``):` `        ``# Find the minimum element``        ``# in unsorted array``        ``min_idx ``=` `i``        ``for` `j ``in` `range``(i ``+` `1``, n):``            ``if` `(arr[j] < arr[min_idx]):``                ``min_idx ``=` `j` `        ``# Swap the found minimum element``        ``# with the first element``        ``arr[min_idx], arr[i] ``=` `arr[i], arr[min_idx]` `# Function to print an array``def` `printArray(arr, size):` `    ``for` `i ``in` `range``(size):``        ``print``(arr[i], end ``=` `" "``)` `    ``print``()` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``64``, ``25``, ``12``, ``22``, ``11``]``    ``n ``=` `len``(arr)` `    ``# Function Call``    ``selectionSort(arr, n)``    ``print``(``"Sorted array: "``)` `    ``# Print the array``    ``printArray(arr, n)` `# This code is contributed by ukasp`

## C#

 `// C# program for implementation of``// selection sort``using` `System;``public` `class` `GFG``{` `// Function to implement the selection``// sort``static` `void` `selectionSort(``int` `[]arr, ``int` `n)``{``    ``int` `i, j, min_idx;` `    ``// One by one move boundary of``    ``// unsorted subarray``    ``for` `(i = 0; i < n - 1; i++)``    ``{` `        ``// Find the minimum element``        ``// in unsorted array``        ``min_idx = i;``        ``for` `(j = i + 1; j < n; j++)``            ``if` `(arr[j] < arr[min_idx])``                ``min_idx = j;` `        ``// Swap the found minimum element``        ``// with the first element``        ``int` `temp = arr[min_idx];``        ``arr[min_idx]= arr[i];``        ``arr[i] = temp;``    ``}``}` `// Function to print an array``static` `void` `printArray(``int` `[]arr, ``int` `size)``{``    ``int` `i;` `    ``for` `(i = 0; i < size; i++) {``        ``Console.Write(arr[i]+ ``" "``);``    ``}``    ``Console.WriteLine();``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { 64, 25, 12, 22, 11 };``    ``int` `n = arr.Length;` `    ``// Function Call``    ``selectionSort(arr, n);``    ``Console.Write(``"Sorted array: \n"``);` `    ``// Print the array``    ``printArray(arr, n);``}``}` `// This code is contributed by gauravrajput1`

## Javascript

 ``

Output:

```Sorted array:
11 12 22 25 64```

Tabular Difference between Insertion Sort and Selection Sort:

My Personal Notes arrow_drop_up