Data Structure & Algorithm in Java

⌘K
  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Sorting
  5. Sorting Algorithms

Sorting Algorithms

Sorting Algorithms are essential tools in computer science used to arrange elements of a list or array in a specific order. There are numerous sorting algorithms, each with its own set of advantages and disadvantages in terms of efficiency, stability, and space complexity.

Screenshot 2024 03 21 182304

Here are some common sorting algorithms:

Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. It continues iterating until the list is sorted. While simple to implement, it is not efficient, especially for large lists.

Selection sort divides the list into two parts: sorted and unsorted. It repeatedly selects the smallest (or largest, depending on the sorting order) element from the unsorted part and moves it to the sorted part. It has a time complexity of O(n^2), making it inefficient for large lists but is often considered easier to understand than other sorting algorithms.

Insertion sort builds the sorted list one element at a time by iteratively placing each element in its correct position relative to the elements that have already been sorted. It is efficient for small lists or nearly sorted lists but becomes slow for large lists due to its time complexity of O(n^2).

Merge sort is a divide-and-conquer algorithm that recursively divides the list into smaller sub lists, sorts them independently, and then merges them back together in sorted order. It has a time complexity of O(n log n) and is stable, meaning it preserves the relative order of equal elements.

Quick sort also uses a divide-and-conquer approach but selects a pivot element, partitions the list into two sub lists based on the pivot, and recursively sorts the sub lists. It has an average-case time complexity of O(n log n) but can degrade to O(n^2) for certain pivot selections. It is often faster in practice than other O(n log n) sorting algorithms.

Heap sort builds a binary heap from the list and repeatedly extracts the maximum (for max heap) or minimum (for min heap) element from the heap and rebuilds the heap until the list is sorted. It has a time complexity of O(n log n) and is often used when a stable sort is not required.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *