📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Selection Sort Overview
How Selection Sort Works?
Advantages
- Easy to implement
- In-place sort (requires no additional storage space)
Disadvantages
- Doesn’t scale well: O(n2)
Selection Sort Algorithm Implementation in Java
import java.util.Arrays;
/**
* Class demonstrate the Selection sort algorithm
* @author Ramesh Fadatare
*
*/
public class SelectionSort {
void selectionSort(int arr[]) {
int size = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < size - 1; i++) {
// Find the minimum element in unsorted array
int minIndex = i;
for (int j = i + 1; j < size; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
// Swap the found minimum element with the first
// element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Driver code to test above
public static void main(String args[]) {
SelectionSort selectionSortb = new SelectionSort();
int arr[] = { 20,10,5,6,2,3,4};
System.out.println("Before Sorting an array : " + Arrays.toString(arr));
selectionSortb.selectionSort(arr);
System.out.println("After Sorting an array : " + Arrays.toString(arr));
}
}
Before Sorting an array : [20, 10, 5, 6, 2, 3, 4]
After Sorting an array : [2, 3, 4, 5, 6, 10, 20]
Performance
- Worst case complexity: O(n2)
- Best case complexity: O(n2)
- Average case complexity: O(n2)
- Worst case space complexity: O(1) auxiliary
Comments
Post a Comment
Leave Comment