DEV Community

Sruthika Ramachandran
Sruthika Ramachandran

Posted on • Edited on

Different Sorting Methodologies

Introduction

Sorting is one of the most fundamental operations in computer science.
It involves arranging data in a specific order (ascending or descending).

Efficient sorting helps improve the performance of searching and data processing tasks.

In this blog, we will explore three basic sorting algorithms:

  • Bubble Sort
  • Selection Sort
  • Insertion Sort

1. Bubble Sort

Concept

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.

Larger elements “bubble up” to the end of the list.

Algorithm

  1. Compare adjacent elements
  2. Swap if needed
  3. Repeat for all elements
  4. Continue until array is sorted

Code (Python)

def bubble_sort(arr):
    n = len(arr)

    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n²)
  • Space: O(1)

Key Point

  • Simple to understand
  • Not efficient for large data

2. Selection Sort

Concept

Selection Sort selects the smallest element from the unsorted part and places it at the correct position.

Algorithm

  1. Find minimum element
  2. Swap it with first element
  3. Repeat for remaining array

Code (Python)

def selection_sort(arr):
    n = len(arr)

    for i in range(n):
        min_index = i

        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]

    return arr
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n²)
  • Space: O(1)

Key Point

  • Fewer swaps compared to Bubble Sort
  • Still inefficient for large inputs

3. Insertion Sort

Concept

Insertion Sort builds the sorted array one element at a time by inserting elements into their correct position.

Algorithm

  1. Take one element
  2. Compare with previous elements
  3. Insert it in correct position
  4. Repeat for all elements

Code (Python)

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1

        arr[j + 1] = key

    return arr
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n²)
  • Space: O(1)

Key Point

  • Efficient for small or nearly sorted data
  • Used in real-world hybrid algorithms

Conclusion

Sorting algorithms are essential building blocks in programming.

  • Bubble Sort is easiest to understand
  • Selection Sort reduces swaps
  • Insertion Sort is efficient for small datasets.

Top comments (0)