Sorting Algorithms Overview
Common Sorting Algorithms in Java
Java supports various sorting algorithms, each with unique characteristics and use cases:
| Algorithm |
Time Complexity |
Space Complexity |
Stability |
| Bubble Sort |
O(n²) |
O(1) |
Stable |
| Quick Sort |
O(n log n) |
O(log n) |
Unstable |
| Merge Sort |
O(n log n) |
O(n) |
Stable |
| Insertion Sort |
O(n²) |
O(1) |
Stable |
| Heap Sort |
O(n log n) |
O(1) |
Unstable |
Sorting Algorithm Visualization
graph TD
A[Sorting Algorithms] --> B[Comparison-Based]
A --> C[Non-Comparison Based]
B --> D[Bubble Sort]
B --> E[Quick Sort]
B --> F[Merge Sort]
C --> G[Radix Sort]
C --> H[Counting Sort]
Implementation Example: Bubble Sort
public class BubbleSortExample {
public 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]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
}
}
Advanced Sorting Techniques
Quick Sort Implementation
public class QuickSortExample {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
}
private 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 elements
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Place pivot in correct position
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
Choosing the Right Algorithm
Algorithm Selection Criteria
- Data size
- Time complexity requirements
- Memory constraints
- Stability needs
- Small datasets: Insertion Sort
- Large datasets: Quick Sort or Merge Sort
- Nearly sorted data: Insertion Sort
- Consistent performance: Merge Sort
LabEx Recommendation
Practice these sorting algorithms in the LabEx Java programming environment to gain practical experience and deep understanding.
Key Takeaways
- Understand different sorting algorithm characteristics
- Choose algorithms based on specific requirements
- Consider time and space complexity
- Practice implementation and optimization