Sorting Algorithms in Java: Bubble, Selection and Insertion Sort Explained


Sorting Algorithms in Java (Complete Guide for Beginners to Interview Level)


Introduction

Sorting ka matlab hota hai data ko kisi specific order me arrange karna.

Example:

Ascending Order → 10, 20, 30, 40
Descending Order → 40, 30, 20, 10

Sorting DSA ka extremely important topic hai kyunki:

  • Searching fast ho jata hai

  • Data organized ho jata hai

  • Interview me frequently poocha jata hai

Almost har software system internally sorting use karta hai.


What is Sorting?

Definition

Sorting is the process of arranging elements of a data structure, such as an array or list, into a specific logical order based on a comparison criteria. The order can be ascending (small to large), descending (large to small), or any custom condition. Sorting improves data organization and makes other operations like searching, analysis, and reporting more efficient. In computer science, sorting algorithms use comparison and swapping techniques to systematically reorder elements while minimizing time and space complexity.

Matlab:

Hum elements ko compare karke unhe logical order me arrange karte hain.


Real Life Examples

📚 Example 1 – Exam Result

School me marks ke hisaab se students ko rank diya jata hai.

Ye sorting hai.


🛒 Example 2 – E-commerce Website

Amazon par “Price: Low to High” select karte ho.

Ye sorting algorithm ka result hai.


Why Sorting Important?

  1. Binary search use karne ke liye array sorted hona chahiye

  2. Data analysis easy hota hai

  3. Efficient data processing possible hoti hai

  4. Interview me common question hai


Types of Sorting Algorithms (Basic Level)

  1. Bubble Sort

  2. Selection Sort

  3. Insertion Sort

Baad me advanced aayenge:

  1. Merge Sort

  2. Quick Sort


Bubble Sort

Definition

Selection Sort is a comparison-based sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the array and placing it at its correct position. It divides the array into two parts: sorted and unsorted. In each iteration, the algorithm scans the remaining unsorted elements to find the minimum value and swaps it with the first unsorted position. Selection Sort has a time complexity of O(n²) in all cases, making it less efficient for large datasets.

Bubble Sort ek simple comparison-based sorting algorithm hai jisme adjacent elements compare hote hain aur galat order me hone par swap kiye jate hain.

Ye process repeat hota hai jab tak array sorted na ho jaye.


Real Example

Socho 5 log height ke hisaab se line me khade hain.

Agar 1st aur 2nd galat order me hain → swap
Fir 2nd aur 3rd compare
Fir 3rd aur 4th

Har round me sabse bada element end me chala jata hai.


Java Code

public class BubbleSort { public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; for(int i = 0; i < arr.length - 1; i++) { for(int j = 0; j < arr.length - i - 1; j++) { if(arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for(int num : arr) { System.out.print(num + " "); } } }

Time Complexity

Worst Case → O(n²)
Best Case → O(n) (if optimized)


 Selection Sort

Definition

Selection Sort me har iteration me smallest element find karke usse correct position par place kiya jata hai.

Insertion Sort is a sorting algorithm that builds the sorted array one element at a time. It works by taking each element from the unsorted portion and inserting it into its correct position within the sorted portion of the array. The algorithm is similar to how people arrange playing cards in their hands. It is efficient for small datasets and nearly sorted arrays, with a best-case time complexity of O(n) and worst-case time complexity of O(n²).


Real Life Example

Socho tum class me shortest student ko first position par khada kar rahe ho.

Fir remaining me se next shortest ko second position par.

Ye selection sort hai.


Java Code

public class SelectionSort { public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; for(int i = 0; i < arr.length - 1; i++) { int minIndex = i; for(int j = i + 1; j < arr.length; j++) { if(arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } for(int num : arr) { System.out.print(num + " "); } } }

Time Complexity

Best Case → O(n²)
Worst Case → O(n²)


 Insertion Sort

Definition

Insertion Sort me hum array ko do parts me divide karte hain:

  • Sorted part

  • Unsorted part

Har iteration me ek element ko sorted part me correct position par insert karte hain.


Real Life Example

Socho tum playing cards arrange kar rahe ho.

Har new card ko sahi jagah insert karte ho.

Ye insertion sort hai.


Java Code

public class InsertionSort { public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; for(int i = 1; i < arr.length; 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; } for(int num : arr) { System.out.print(num + " "); } } }

Time Complexity

Best Case → O(n)
Worst Case → O(n²)


Comparison Table

AlgorithmBest CaseWorst CaseStable
Bubble SortO(n)O(n²)Yes
Selection SortO(n²)O(n²)No
Insertion SortO(n)O(n²)Yes

Which One Should Beginners Focus On?

✔ Concept clear karne ke liye teeno
✔ Interviews me basic understanding required
✔ Real systems me advanced sorting use hota hai


Conclusion

Sorting algorithms data ko organized banate hain.
Basic sorting algorithms concept build karte hain.

Next article me hum Merge Sort and Quick Sort (Advanced Sorting) detail me samjhenge.

Comments

Popular posts from this blog

Binary Tree in Data Structures Explained in Depth (Concept, Types and Java Implementation)

Binary Tree Traversal Explained in Depth (Preorder, Inorder, Postorder with Java Code)

Recursion in Java Explained with Examples (Base Case, Recursive Case & Dry Run Guide)