For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Sorting algorithms are essential building blocks in the field of computer science and software development. They are used to arrange data in a particular order—usually numerical or lexicographical—which is crucial for efficient searching, data analysis, and enhancing user experience.
Whether you're filtering products by price on an e-commerce site, processing leaderboard rankings in a game, or organizing records in a database, sorting ensures that data remains manageable and accessible.
Selection Sort stands out for its simplicity and educational value among the wide array of sorting techniques. While it may not be the most efficient in real-world applications, it serves as an excellent introduction to the inner workings of sorting logic.
Selection Sort follows a clear, step-by-step approach, making it easy for beginners to visualize and understand the sorting process.
In this blog, we’ll explain how the algorithm works, walk through its implementation with code examples, and analyze its time and space complexity.
You can also explore our in-depth Software engineering courses.
To understand how selection sort works, consider the following steps:
Here’s a simple example:
Given an array [64, 25, 12, 22, 11]:
Boost your skills by enrolling in these top-rated programs:
Let’s now implement this logic using Java. The following is a simple implementation of selection sort in Java:
public class SelectionSortExample {
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;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] data = {64, 25, 12, 22, 11};
selectionSort(data);
System.out.println("Sorted array:");
for (int value : data) {
System.out.print(value + " ");
}
}
}
Explanation:
In this implementation of selection sort Java, the outer loop iterates through the array elements one by one. For each element, the inner loop finds the minimum value from the unsorted portion of the array.
Once the minimum is found, it is swapped with the current element at the outer loop's index. This process ensures that with every iteration, one element is placed in its correct sorted position.
This is a classic implementation that helps in understanding how selection sort algorithm works step by step.
Must read: Loops in Java
When considering any algorithm for real-world use, understanding its efficiency is crucial. Let’s analyze the time and space complexity of selection sort in Java.
While the quadratic time complexity makes it inefficient for large datasets, the selection sort Java implementation is still widely used in teaching sorting basics because of its simplicity.
Must read: Bubble Sort in Java
Besides the standard integer-based approach, Java allows developers to implement selection sort in a more flexible way using generics. This approach allows for sorting objects like strings or custom classes, as long as they implement the Comparable interface.
Here’s a generic version of selection sort in Java:
public class GenericSelectionSort {
public static <T extends Comparable<T>> void selectionSort(T[] 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].compareTo(arr[minIndex]) < 0) {
minIndex = j;
}
}
T temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
String[] words = {"banana", "apple", "orange", "kiwi"};
selectionSort(words);
System.out.println("Sorted array:");
for (String word : words) {
System.out.print(word + " ");
}
}
}
Even though selection sort is not as efficient as Quick Sort or Merge Sort for large datasets, it offers some clear benefits:
In the context of small datasets or systems with very limited memory, selection sort Java can be a practical choice.
Also explore: Insertion Sort in Java
Although Selection Sort is not the go-to choice for sorting large volumes of data, it still finds practical use in certain scenarios where simplicity, predictability, and low memory usage are more valuable than speed.
Here are some real-world contexts where selection sort in Java (or in general) proves useful:
Selection Sort is widely used in academic settings to teach fundamental sorting logic. Its step-by-step process makes it easy for students to visualize and understand key concepts like comparisons, swapping, and in-place sorting. In Java, its simplicity allows beginners to focus on learning algorithm structure without getting overwhelmed by complexity.
In embedded systems such as microcontrollers or IoT devices, memory is often extremely limited. Selection Sort, being an in-place algorithm with O(1) space complexity, becomes a practical choice when dealing with small datasets, especially when additional memory allocation is not feasible.
For small datasets where performance is not a critical concern, the overhead of more complex algorithms may be unnecessary. Selection Sort can handle such cases with minimal code and predictable behavior. Additionally, if the data is already nearly sorted, the number of swaps (which are relatively few in Selection Sort) helps keep operations efficient.
Selection Sort in Java stands as a testament to the elegance of simple algorithms.
Though not the most efficient for large-scale data operations, its clarity, minimal memory usage, and deterministic behavior make it a reliable option for specific use cases—particularly where ease of implementation matters more than performance.
Whether you're working within resource-constrained environments or just beginning your journey into algorithmic thinking, mastering selection sort offers a strong foundation. It encourages a deeper understanding of how sorting works at the core and prepares you to appreciate the complexity and power of more advanced sorting techniques down the line.
Selection sort in Java works by repeatedly finding the minimum element from the unsorted portion of an array and swapping it with the first unsorted element. This process continues until the array is completely sorted. It is a simple, intuitive sorting method that teaches important programming concepts like nested loops and conditionals.
No, selection sort is not a stable sorting algorithm by default. It can change the relative order of equal elements during the swapping process. This makes it unsuitable for scenarios where maintaining the original sequence of duplicate values is important.
You should consider using selection sort in Java when working with small datasets or when simplicity is more important than efficiency. It’s particularly useful in low-memory environments or for educational and demonstrative purposes. For larger datasets or performance-critical tasks, more efficient algorithms like Merge Sort or Quick Sort are recommended.
Selection sort has a time complexity of O(n²), meaning its execution time increases significantly as the number of elements grows. This is because each element is compared with every other element in the array. For large datasets, this leads to noticeable performance delays and inefficient processing.
No, selection sort is an in-place sorting algorithm, which means it does not require additional memory beyond the original array. All operations are performed by swapping elements within the array itself. This makes it memory-efficient and suitable for environments with strict space constraints.
Yes, you can implement selection sort for Strings or any object that implements the Comparable interface in Java. By using generics and compareTo(), you can sort arrays of strings, custom classes, or other comparable types. This makes the algorithm flexible for use beyond just primitive data types.
While both are simple comparison-based sorting algorithms, selection sort makes fewer swaps than bubble sort. Bubble sort repeatedly swaps adjacent elements if they’re in the wrong order, leading to more overall movement. Selection sort, on the other hand, selects the minimum and swaps only once per iteration, which can be more efficient in terms of write operations.
Yes, you can easily modify selection sort to sort in descending order by adjusting the comparison condition. Instead of finding the minimum element, you look for the maximum element in the unsorted portion. The rest of the logic remains the same, making it a very adaptable algorithm.
Selection sort performs at most n-1 swaps, where n is the number of elements in the array. This is because each element is swapped only once into its correct position. Compared to other sorting algorithms like bubble sort, this makes selection sort more efficient in terms of swap operations.
Learning selection sort in Java helps build a solid foundation in understanding algorithmic problem-solving and sorting mechanics. It reinforces basic programming constructs like loops, conditionals, and array handling. Although not used in high-performance applications, it’s a critical step in becoming proficient in data structures and algorithms.
Yes, selection sort can be adapted for linked lists, although the implementation is more complex than with arrays. You would need to traverse the list to find the minimum node and rearrange pointers instead of swapping elements. However, other sorting algorithms like Merge Sort are generally more efficient for linked lists.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Disclaimer
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.