Java Sorting Algorithms — Free Java Tutorial
Learn Java Sorting Algorithms in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Sorting Algorithms in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Sorting Algorithms in Java
Bubble Sort: repeatedly swaps adjacent elements if in wrong order. O(n²) time, O(1) space. Simple but slow — good for teaching, not production.
Selection Sort: finds the minimum element and places it at the front repeatedly. O(n²) time, O(1) space. Makes fewer swaps than bubble sort.
Insertion Sort: builds a sorted portion one element at a time (like sorting playing cards). O(n²) worst, O(n) best (nearly sorted). Efficient for small/nearly-sorted data.
Merge Sort: divide-and-conquer — split into halves, sort each, merge. O(n log n) time, O(n) space. Stable and efficient.
Java Sorting Algorithms — Syntax
// Bubble Sort
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-1-i; j++)
if (arr[j] > arr[j+1]) swap(arr, j, j+1);
// Merge Sort
void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
Learn Java Sorting Algorithms step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →