Common Sorting Methods
Overview of Sorting Algorithms
Basic Sorting Techniques in Java
1. Bubble Sort
public class BubbleSort {
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;
}
}
}
}
}
2. Selection Sort
public class SelectionSort {
public 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;
}
}
// Swap elements
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
3. Insertion Sort
public class InsertionSort {
public 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 = j - 1;
}
arr[j + 1] = key;
}
}
}
Advanced Sorting Methods
Quick Sort
public class QuickSort {
public 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);
}
}
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;
}
}
Sorting Method Comparison
Sorting Method |
Time Complexity (Average) |
Space Complexity |
Stability |
Bubble Sort |
O(n²) |
O(1) |
Yes |
Selection Sort |
O(n²) |
O(1) |
No |
Insertion Sort |
O(n²) |
O(1) |
Yes |
Quick Sort |
O(n log n) |
O(log n) |
No |
Sorting Visualization
graph TD
A[Unsorted Array] --> B{Sorting Algorithm}
B -->|Bubble Sort| C[Sorted Array]
B -->|Quick Sort| D[Sorted Array]
B -->|Insertion Sort| E[Sorted Array]
Practical Considerations
At LabEx, we recommend:
- Choose sorting method based on data size
- Consider time and space complexity
- Use built-in Java sorting methods for most scenarios
Key Takeaways
- Multiple sorting techniques exist
- Each method has unique characteristics
- Understanding trade-offs is crucial for efficient sorting