Sorting Algorithms: Selection, Insertion and Bubble Sort
1. Selection Sort
- Select the minimum element and swap to correct position.
- Time Complexity: Best = Average = Worst = O(n^2)
- Not Stable
- Simple but inefficient for large data
Java Code:
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;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
2. Insertion Sort
- Builds sorted part one by one by shifting elements.
- Time Complexity: Best = O(n), Worst = O(n^2)
- Stable
- Good for nearly sorted data
Java Code:
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--;
}
arr[j+1] = key;
}
3. Bubble Sort
- Repeatedly compare adjacent values and swap if needed.
- Optimized using swapped flag.
- Time Complexity: Best = O(n), Worst = O(n^2)
- Stable but slow
Java Code:
for(int i=0; i<n-1; i++){
boolean swapped = false;
for(int j=0; j<n-i-1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
}
if(!swapped) break;