Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A QuizIntroduction to Sorting Algorithms
Sorting is a fundamental operation in computer science that
arranges data in a particular order—typically ascending or descending.
Efficient sorting is crucial for optimizing performance in searching, data
processing, and algorithmic problem-solving. Java provides various sorting
algorithms, each with its own advantages and applications.
This tutorial explores Bubble Sort, Selection Sort,
Insertion Sort, Merge Sort, and Quick Sort with Java implementations,
complexity analysis, comparisons, and real-world applications.
Comparison of Sorting Algorithms
The table below provides a comparison of different
sorting algorithms based on time complexity, space complexity, and
stability:
Sorting Algorithm |
Best Case |
Average Case |
Worst Case |
Space Complexity |
Stable? |
Bubble Sort |
O(n) |
O(n²) |
O(n²) |
O(1) |
✅ Yes |
Selection Sort |
O(n²) |
O(n²) |
O(n²) |
O(1) |
❌ No |
Insertion Sort |
O(n) |
O(n²) |
O(n²) |
O(1) |
✅ Yes |
Merge Sort |
O(n log n) |
O(n log n) |
O(n log n) |
O(n) |
✅ Yes |
Quick Sort |
O(n log n) |
O(n log n) |
O(n²) |
O(log n) (avg.) |
❌ No |
Sorting Algorithms with Java Implementation
1. Bubble Sort
Bubble Sort is a simple algorithm that repeatedly steps
through the list, compares adjacent elements, and swaps them if they are in the
wrong order. This process repeats until the list is sorted.
Java Implementation:
public
class BubbleSort {
static void bubbleSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1;
j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String args[]) {
int arr[] = {64, 25, 12, 22, 11};
bubbleSort(arr);
System.out.println(java.util.Arrays.toString(arr));
}
}
Time Complexity:
Space Complexity: O(1)
2. Selection Sort
Selection Sort repeatedly finds the minimum element from the
unsorted portion and swaps it with the first unsorted element.
Java Implementation:
public
class SelectionSort {
static void selectionSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String args[]) {
int arr[] = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println(java.util.Arrays.toString(arr));
}
}
Time Complexity:
Space Complexity: O(1)
3. Insertion Sort
Insertion Sort builds the sorted array one element at a time
by inserting each new element into its correct position.
Java Implementation:
public
class InsertionSort {
static void insertionSort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j]
> key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void main(String args[]) {
int arr[] = {64, 25, 12, 22, 11};
insertionSort(arr);
System.out.println(java.util.Arrays.toString(arr));
}
}
Time Complexity:
Space Complexity: O(1)
4. Merge Sort
Merge Sort is a divide and conquer algorithm that
splits the array into halves, sorts each half, and merges them back.
Java Implementation:
public
class MergeSort {
static void mergeSort(int arr[], int left,
int right) {
if (left < right) {
int mid = left + (right - left) /
2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
static void merge(int arr[], int left, int
mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int leftArray[] = new int[n1];
int rightArray[] = new int[n2];
System.arraycopy(arr, left, leftArray,
0, n1);
System.arraycopy(arr, mid + 1,
rightArray, 0, n2);
int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if (leftArray[i] <=
rightArray[j]) {
arr[k] = leftArray[i++];
} else {
arr[k] = rightArray[j++];
}
k++;
}
while (i < n1) arr[k++] =
leftArray[i++];
while (j < n2) arr[k++] =
rightArray[j++];
}
public static void main(String args[]) {
int arr[] = {64, 25, 12, 22, 11};
mergeSort(arr, 0, arr.length - 1);
System.out.println(java.util.Arrays.toString(arr));
}
}
Time Complexity:
Space Complexity: O(n)
5. Quick Sort
Quick Sort selects a pivot, partitions the array around the
pivot, and recursively sorts the partitions.
Java Implementation:
public
class QuickSort {
static void quickSort(int arr[], int low,
int high) {
if (low < high) {
int pivotIndex = partition(arr,
low, high);
quickSort(arr, low, pivotIndex -
1);
quickSort(arr, pivotIndex + 1,
high);
}
}
static int partition(int arr[], int low,
int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void main(String args[]) {
int arr[] = {64, 25, 12, 22, 11};
quickSort(arr, 0, arr.length - 1);
System.out.println(java.util.Arrays.toString(arr));
}
}
Time Complexity:
Space Complexity: O(log n)
Final Thoughts
This tutorial provides a comprehensive guide on sorting
algorithms, their implementations, and comparisons. Whether you're a beginner
or an experienced programmer, mastering sorting algorithms will enhance your
problem-solving skills. 🚀
Bubble Sort repeatedly compares adjacent elements and swaps
them if they are in the wrong order. This leads to O(n²) time complexity,
making it highly inefficient for large datasets. The excessive number of swaps
and comparisons makes it slow compared to Merge Sort (O(n log n)) or Quick
Sort (O(n log n)).
Quick Sort is preferred in many scenarios because:
Insertion Sort is best for nearly sorted data
because:
A sorting algorithm is stable if it preserves the
relative order of elements with equal values.
Stable sorting algorithms in our list:
✅
Bubble Sort
✅
Insertion Sort
✅
Merge Sort
🚫
Selection Sort (can swap elements with the same value)
🚫
Quick Sort (depends on implementation)
Yes! We can optimize Bubble Sort by introducing a swap
flag:
Optimized Bubble Sort in Java:
static
void optimizedBubbleSort(int arr[]) {
int n = arr.length;
boolean 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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // Stop if already sorted
}
}
This optimization improves performance significantly when
the input is partially sorted.
Quick Sort's worst-case occurs when:
To avoid this, randomized pivot selection or choosing
the median pivot is recommended.
Merge Sort is preferred for linked lists because:
Selection Sort is not stable because:
To make it stable, we can modify Selection Sort by
using linked lists or keeping track of indexes instead of swapping values
directly.
Merge Sort requires O(n) extra space because:
Optimizations to reduce space:
Yes, sorting can be done in O(n) time, but only for special
cases, such as:
These non-comparison sorts work by categorizing elements
into buckets instead of using comparisons (O(n log n) is the lower bound
for comparison-based sorts).
Posted on 16 Apr 2025, this text provides information on Algorithms. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.
Introduction In today's highly competitive tech job market, Data Structures and Algorithms (DSA)...
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)