0% found this document useful (0 votes)
5 views1 page

Sorting Algorithms: Selection, Insertion, Bubble

The document discusses three sorting algorithms: Selection Sort, Insertion Sort, and Bubble Sort. Each algorithm is described with its method, time complexity, stability, and a Java code implementation. Selection Sort is inefficient for large data, Insertion Sort is effective for nearly sorted data, and Bubble Sort is stable but slow.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Sorting Algorithms: Selection, Insertion, Bubble

The document discusses three sorting algorithms: Selection Sort, Insertion Sort, and Bubble Sort. Each algorithm is described with its method, time complexity, stability, and a Java code implementation. Selection Sort is inefficient for large data, Insertion Sort is effective for nearly sorted data, and Bubble Sort is stable but slow.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;

You might also like