- Bubble Sort
- Quick Sort
- Merge Sort
Sorting
Sorting is the process of arranging elements in a particular order — either ascending or descending. It is one of the most common operations performed on arrays in programming.
Sorting helps in:
- Searching faster
- Understanding data patterns
- Improving performance of other algorithms
Bubble Sort in Java
Bubble Sort is the simplest sorting algorithm. It repeatedly compares and swaps adjacent elements if they are in the wrong order.
Code–
public class BubbleSort { public static void main(String[] args) { int[] arr = {8, 4, 1, 56, 3, 2}; 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]) { // swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } // Print sorted array for (int num : arr) { System.out.print(num + " "); } } }
OUTPUT: 1 2 3 4 8 56
Quick Sort
Quick Sort is a divide-and-conquer algorithm. It selects a pivot and partitions the array such that elements less than pivot are on the left, and greater on the right.
Code–
public class QuickSort { public static void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } public 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++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } public static void main(String[] args) { int[] arr = {8, 4, 1, 56, 3, 2}; quickSort(arr, 0, arr.length - 1); for (int num : arr) { System.out.print(num + " "); } } }
OUTPUT: 1 2 3 4 8 56
Merge Sort
Merge Sort also uses divide-and-conquer. It divides the array, sorts both halves, and then merges them.
Code–
public class MergeSort { public static void mergeSort(int[] arr, int left, int right) { if (left < right) { int mid = (left + right) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } } public static void merge(int[] arr, int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid; int[] L = new int[n1]; int[] R = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[left + i]; for (int j = 0; j < n2; ++j) R[j] = arr[mid + 1 + j]; int i = 0, j = 0; int k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k++] = L[i++]; } else { arr[k++] = R[j++]; } } while (i < n1) { arr[k++] = L[i++]; } while (j < n2) { arr[k++] = R[j++]; } } public static void main(String[] args) { int[] arr = {8, 4, 1, 56, 3, 2}; mergeSort(arr, 0, arr.length - 1); for (int num : arr) { System.out.print(num + " "); } } }
OUTPUT: 1 2 3 4 8 56