Introduction to Sorting Techniques
Last Updated :
26 Jul, 2025
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure.
Why Sorting Algorithms are Important
Sorting algorithms are essential in Computer Science as they simplify complex problems and improve efficiency. They are widely used in searching, databases, divide and conquer strategies, and data structures.
Key Applications:
- Organizing large datasets for easier handling and printing
- Enabling quick access to the k-th smallest or largest elements
- Making binary search possible for fast lookups in sorted data
- Solving advanced problems in both software and algorithm design
Sorting Basics
- In-place Sorting: An in-place sorting algorithm uses constant space for producing the output (modifies the given array only. Examples: Selection Sort, Bubble Sort, Insertion Sort and Heap Sort.
- Internal Sorting: Internal Sorting is when all the data is placed in the main memory or internal memory. In internal sorting, the problem cannot take input beyond allocated memory size.
- External Sorting : External Sorting is when all the data that needs to be sorted need not to be placed in memory at a time, the sorting is called external sorting. External Sorting is used for the massive amount of data. For example Merge sort can be used in external sorting as the whole array does not have to be present all the time in memory,
- Stable sorting: When two same items appear in the same order in sorted data as in the original array called stable sort. Examples: Merge Sort, Insertion Sort, Bubble Sort.
- Hybrid Sorting: A sorting algorithm is called Hybrid if it uses more than one standard sorting algorithms to sort the array. The idea is to take advantages of multiple sorting algorithms. For Example IntroSort uses Insertions sort and Quick Sort.
Types of Sorting Techniques
There are various sorting algorithms are used in data structures. The following two types of sorting algorithms can be broadly classified:
- Comparison-based: We compare the elements in a comparison-based sorting algorithm)
- Non-comparison-based: We do not compare the elements in a non-comparison-based sorting algorithm)
Sorting algorithmBasics Sorting Algorithms:
Bubble Sort - O(n^2) Time and O(1) Space
It is a simple sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong order. It performs multiple passes through the array, and in each pass, the largest unsorted element moves to its correct position at the end.
After each pass, we ignore the last sorted elements and continue comparing and swapping remaining adjacent pairs. After k passes, the last k elements are sorted. For more details refer here.
C++
#include <iostream>
#include <vector>
using namespace std;
// An optimized version of Bubble Sort
void bubbleSort(vector<int>& arr) {
int n = arr.size();
bool swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
// If no two elements were swapped, then break
if (!swapped)
break;
}
}
int main() {
vector<int> arr = { 5, 6, 1, 3 };
bubbleSort(arr);
for (int num : arr)
cout << num << " ";
}
Java
// Optimized java implementation of Bubble sort
class GFG {
// An optimized version of Bubble Sort
static void bubbleSort(int arr[], int n){
int i, j, temp;
boolean swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
public static void main(String args[]){
int arr[] = { 5, 6, 1, 3 };
int n = arr.length;
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Optimized Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if (swapped == False):
break
if __name__ == "__main__":
arr = [5, 6, 1, 3]
bubbleSort(arr)
for i in range(len(arr)):
print("%d" % arr[i], end=" ")
C#
// Optimized C# implementation of Bubble sort
using System;
class GFG {
static void bubbleSort(int[] arr, int n){
int i, j, temp;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
public static void Main(){
int[] arr = { 5, 6, 1, 3 };
int n = arr.Length;
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
// Optimized javaScript implementation
// of Bubble sort
function bubbleSort(arr){
var i, j, temp;
var swapped;
var n = arr.length;
for (i = 0; i < n - 1; i++){
swapped = false;
for (j = 0; j < n - i - 1; j++){
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
// Driver program
var arr = [5, 6, 1, 3];
bubbleSort(arr);
console.log(...arr);
Output11 12 22 25 34 64 90
Insertion Sort - O(n^2) Time and O(1) Space
It is a simple sorting algorithm that builds the sorted array one element at a time. It works like sorting playing cards in your hand, where each new card is inserted into its correct position among the already sorted cards.
We start with the second element, assuming the first is already sorted. If the second element is smaller, we shift the first element and insert the second in the correct position. Then we move to the third element and place it correctly among the first two. This process continues until the entire array is sorted. For more details refer here.
C++
#include <iostream>
#include <vector>
using namespace std;
void insertionsort(vector<int>& arr, int n) {
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
// move elements greater than key one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
vector<int> arr = {12, 11, 13, 5, 6};
int n = arr.size();
insertionsort(arr, n);
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Java
public class GfG {
static void insertionSort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int 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;
}
}
public static void main(String args[]) {
int arr[] = { 12, 11, 13, 5, 6 };
insertionSort(arr);
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i] + " ");
}
}
Python
def insertionSort(arr):
for i in range(1, len(arr)):
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 key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
if __name__ == "__main__":
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
C#
using System;
class GfG {
public void insertionSort(int[] arr) {
int n = arr.Length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int 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;
}
}
public static void Main() {
int[] arr = { 12, 11, 13, 5, 6 };
GfG obj = new GfG();
obj.insertionSort(arr);
for (int i = 0; i < arr.Length; ++i)
Console.Write(arr[i] + " ");
}
}
JavaScript
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let key = arr[i];
let 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;
}
}
// Driver method
let arr = [12, 11, 13, 5, 6];
insertionSort(arr);
console.log(arr.join(" "));
Selection Sort - O(n^2) Time and O(1) Space
It is a comparison-based sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted part of the array and swaps it with the first unsorted element. This process continues until the array is fully sorted.
We start by finding the smallest element and swap it with the first element. Then we find the next smallest element among the remaining and swap it with the second element. This continues until all elements are placed in their correct positions. For more details refer here.
C++
#include <iostream>
#include <vector>
using namespace std;
void selectionSort(vector<int> &arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; ++j) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller
// element is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
swap(arr[i], arr[min_idx]);
}
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
selectionSort(arr);
for (int &val : arr) {
cout << val << " ";
}
return 0;
}
Java
import java.util.Arrays;
class GfG {
static void selectionSort(int[] arr){
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element
// is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
selectionSort(arr);
for (int val : arr) {
System.out.print(val + " ");
}
}
}
Python
def selectionSort(arr):
n = len(arr)
for i in range(n - 1):
# Assume the current position holds
# the minimum element
min_idx = i
# Iterate through the unsorted portion
# to find the actual minimum
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
# Update min_idx if a smaller element is found
min_idx = j
# Move minimum element to its
# correct position
arr[i], arr[min_idx] = arr[min_idx], arr[i]
if __name__ == "__main__":
arr = [64, 25, 12, 22, 11]
selectionSort(arr)
for val in arr:
print(val, end=" ")
C#
// C# program for implementation
// of Selection Sort
using System;
class GfG {
static void selectionSort(int[] arr){
int n = arr.Length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element
// is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
public static void Main(){
int[] arr = { 64, 25, 12, 22, 11 };
selectionSort(arr);
foreach(int val in arr){
Console.Write(val + " ");
}
}
}
JavaScript
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
let min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
let temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
// Driver function
const arr = [64, 25, 12, 22, 11];
selectionSort(arr);
for (let val of arr) {
process.stdout.write(val + " ");
}
It is a non-comparison-based sorting algorithm that works efficiently when the range of input values is small relative to the number of elements. It counts the frequency of each distinct element and uses that count to place elements directly into their correct sorted positions.
However, if the maximum value is much larger than the array size (especially more than n log n), then standard comparison-based algorithms are usually more efficient. For more details refer here.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> countsort(vector<int>& arr) {
int n = arr.size();
// find the maximum element
int maxval = 0;
for (int i = 0; i < n; i++)
maxval = max(maxval, arr[i]);
// create and initialize count array
vector<int> count(maxval + 1, 0);
// count frequency of each element
for (int i = 0; i < n; i++)
count[arr[i]]++;
// compute prefix sum
for (int i = 1; i <= maxval; i++)
count[i] += count[i - 1];
// build output array
vector<int> ans(n);
for (int i = n - 1; i >= 0; i--) {
ans[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
return ans;
}
int main() {
vector<int> arr = {2,5,3,0,2,3,0,3};
vector<int> sorted = countsort(arr);
for (int x : sorted)
cout << x << " ";
return 0;
}
Java
import java.util.ArrayList;
class GfG {
public static ArrayList<Integer> countsort(int arr[]) {
int n = arr.length;
// find the maximum element
int maxval = 0;
for (int i = 0; i < n; i++)
if (arr[i] > maxval) maxval = arr[i];
// create and initialize count array
int[] count = new int[maxval + 1];
// count frequency of each element
for (int i = 0; i < n; i++)
count[arr[i]]++;
// compute prefix sum
for (int i = 1; i <= maxval; i++)
count[i] += count[i - 1];
// build output array
int[] ans = new int[n];
for (int i = n - 1; i >= 0; i--) {
ans[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// convert to ArrayList
ArrayList<Integer> result = new ArrayList<>();
for (int x : ans)
result.add(x);
return result;
}
public static void main(String[] args) {
int arr[] = {2,5,3,0,2,3,0,3};
ArrayList<Integer> sorted = countsort(arr);
for (int x : sorted)
System.out.print(x + " ");
}
}
Python
def countsort(arr):
n = len(arr)
# find the maximum element
maxval = max(arr)
# create and initialize count array
count = [0] * (maxval + 1)
# count frequency of each element
for num in arr:
count[num] += 1
# compute prefix sum
for i in range(1, maxval + 1):
count[i] += count[i - 1]
# build output array
ans = [0] * n
for i in range(n - 1, -1, -1):
val = arr[i]
ans[count[val] - 1] = val
count[val] -= 1
return ans
if __name__ == "__main__":
arr = [2,5,3,0,2,3,0,3]
sortedArr = countsort(arr)
print(*sortedArr)
C#
using System;
using System.Collections.Generic;
class GfG {
public static List<int> countsort(int[] arr) {
int n = arr.Length;
// find the maximum element
int maxval = 0;
for (int i = 0; i < n; i++)
maxval = Math.Max(maxval, arr[i]);
// create and initialize count array
int[] count = new int[maxval + 1];
// count frequency of each element
for (int i = 0; i < n; i++)
count[arr[i]]++;
// compute prefix sum
for (int i = 1; i <= maxval; i++)
count[i] += count[i - 1];
// build output array
int[] ans = new int[n];
for (int i = n - 1; i >= 0; i--) {
int val = arr[i];
ans[count[val] - 1] = val;
count[val]--;
}
// convert to List<int>
List<int> result = new List<int>();
foreach (int x in ans)
result.Add(x);
return result;
}
static void Main() {
int[] arr = {2,5,3,0,2,3,0,3};
List<int> sorted = countsort(arr);
foreach (int x in sorted)
Console.Write(x + " ");
}
}
JavaScript
class GfG {
static countsort(arr) {
let n = arr.length;
// find the maximum element
let maxval = Math.max(...arr);
// create and initialize count array
let count = Array(maxval + 1).fill(0);
// count frequency of each element
for (let i = 0; i < n; i++)
count[arr[i]]++;
// compute prefix sum
for (let i = 1; i <= maxval; i++)
count[i] += count[i - 1];
// build output array
let ans = Array(n);
for (let i = n - 1; i >= 0; i--) {
let val = arr[i];
ans[count[val] - 1] = val;
count[val]--;
}
return ans;
}
}
// Driver code
let arr = [2,5,3,0,2,3,0,3];
let sorted = GfG.countsort(arr);
console.log(...sorted);
Time Complexity: O(n + m), where n and m are the size of arr[] and count[] respectively
Auxiliary Space: O(n + m)
Some of the most common sorting algorithms are:
Selection sort, Bubble sort, Insertion Sort, Cycle Sort, Merge Sort, 3-way Merge Sort, Quick sort, Heap sort and Counting sort
Some other Sorting algorithms:
Radix sort, Bucket sort, Shell sort, Tim Sort, Comb Sort, Pigeonhole sorting, Cocktail Sort, Strand sort, Bitonic Sort, Stooge Sort, Tag Sort, Tree sort, Cartesian Sort, Odd-Even Sort / Brick Sort, Gnome sort, Cocktail shaker sort
Comparison of Complexity Analysis of Sorting Algorithms:
Overview of Sorting Algorithms
Stability in Sorting Algorithm
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem