Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
Now Reading
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Selection sort in Java is a simple yet efficient sorting algorithm widely used in Java programming. It provides a straightforward approach to sorting elements in an array or a collection in ascending or descending order.
Selection sort offers a practical and intuitive solution for arranging data in a desired sequence. By understanding the principles behind selection sort and its implementation in Java, you can enhance your programming skills and effectively organize your data.
In this tutorial, we will explore the concept of selection sort in Java, including the selection sort Java ArrayList technique.
The selection sort algorithm is a straightforward sorting method that involves finding the smallest (or largest) element from a section of an array that is yet to be sorted, and exchanging it with the element at the start of the unsorted section, thereby gradually sorting the array.
Here is the step-by-step process of the selection sort algorithm:
Selection sort in Java belongs to the category of comparison-based sorting algorithms and is characterized by its simplicity and ease of implementation. Understanding the inner workings of selection sort is essential for any programmer or computer scientist studying data structures and algorithms.
Here is the step-by-step process of the selection sort algorithm:
Selection sort has a time complexity of O(n^2), where n is the number of elements in the array. It is an in-place sorting algorithm since it requires no additional memory apart from the input array.
Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and swapping it with the element at the beginning of the unsorted part. The algorithm maintains two subarrays: the sorted subarray and the unsorted subarray. The sorted subarray is initially empty, and the unsorted subarray contains all the elements.
The complexity analysis of an algorithm helps us understand how its performance scales with the input size. Let's analyze the complexity of the selection sort algorithm in Java.
Selection sort is a simple comparison-based sorting algorithm. It works by dividing the input array into two parts: the sorted part at the beginning and the unsorted part at the end. In each iteration, the algorithm finds the minimum (or maximum) element from the unsorted part and swaps it with the first element of the unsorted part. This process continues until the entire array is sorted.
Here's the step-by-step breakdown of the selection sort algorithm:
Now let's analyze the complexity of selection sort:
In the best-case scenario, the input array is already sorted. However, selection sort does not take advantage of this fact and still performs the same number of comparisons and swaps as in the average and worst cases. Therefore, the best-case time complexity is still O(n^2).
In the average and worst cases, the outer loop iterates n times, where n is the number of elements in the array. For each iteration, the inner loop performs n - i comparisons, where i is the current iteration index. This results in a total of (n-1) + (n-2) + ... + 1 = (n * (n-1)) / 2 comparisons and swaps.
Thus, the time complexity of the selection sort is O(n^2) in all cases.
Selection sort is an in-place sorting algorithm, meaning it does not require additional memory proportional to the input size. Therefore, the space complexity of the selection sort is O(1) (constant space).
import java.util.Arrays;
public class upGradTutorials {
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 the minimum element with the first element of the unsorted part
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Before sorting: " + Arrays.toString(arr));
selectionSort(arr);
System.out.println("After sorting: " + Arrays.toString(arr));
}
}
In the selectionSort method, the input array arr is passed as a parameter. The algorithm initializes a variable n to store the array's length.
The outer loop iterates from the first element to the second-to-last element of the array. At each iteration, it assumes the current element is the minimum value and assigns its index to the variable minIndex. The inner loop then starts from the next element after the current element and compares each subsequent element with the assumed minimum element. If a smaller element is found, the index of that element is updated in minIndex.
After completing the inner loop, the minimum element in the unsorted part of the array is found. It is then swapped with the first element of the unsorted part by using a temporary variable temp. This process continues until the entire array is sorted, with each iteration finding the minimum element and moving it to the correct position in the sorted portion of the array.
In the main method, an array arr is initialized with some values. The array is then printed before sorting using Arrays.toString(arr). The selectionSort method is called to sort the array. After sorting, the sorted array is printed using Arrays.toString(arr) to display the elements in ascending order.
import java.util.Arrays;
public class upGradTutorials {
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 the elements using XOR operation
arr[i] = arr[i] ^ arr[minIndex];
arr[minIndex] = arr[i] ^ arr[minIndex];
arr[i] = arr[i] ^ arr[minIndex];
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Before sorting: " + Arrays.toString(arr));
selectionSort(arr);
System.out.println("After sorting: " + Arrays.toString(arr));
}
}
This implementation follows the same selection sort algorithm, with slight variation in the element swapping process. Instead of using a temporary variable, it uses the XOR operation to swap the elements
In the selectionSort method, the array is iterated using two nested loops. The outer loop determines the current minimum element's index, and the inner loop compares the remaining elements to find the smallest element.
Once the minimum element is found, the XOR operation swaps the elements without requiring a temporary variable. This is achieved by performing XOR operations on the elements' values. This bitwise operation allows the elements to be swapped in place.
The main method initializes an array with some values, and the selectionSort method is called to sort the array in ascending order. Finally, the sorted array is printed before and after the sorting process.
The selection sort algorithm, although simple, offers a few advantages:
While selection sort has its advantages, it also has several disadvantages:
As the number of elements increases, the sorting time grows quadratically, making it inefficient for large datasets.
Other sorting algorithms like Quicksort or Mergesort offer better performance for large datasets with faster time complexities.
This can be a disadvantage when maintaining the order of equal elements is important.
These redundant comparisons result in unnecessary computational work and inefficiency in the algorithm.
This lack of adaptiveness can make it less efficient than other algorithms that exploit the initial order of the data.
Selection sort is a straightforward sorting algorithm that can be implemented in Java. It operates by iteratively finding the smallest (or largest) element and placing it in its correct position. Selection sort is not the most efficient choice for sorting large datasets, but it can serve as a useful learning tool for understanding sorting algorithms and principles.
Nonetheless, it is a foundational concept in sorting algorithms and provides valuable insights into algorithmic thinking and problem-solving.
1. What is insertion sort in Java?
Insertion sort in Java is a sorting algorithm that iteratively builds a sorted portion of an array by inserting elements into their correct positions.
2, What is bubble sort in Java?
Bubble sort in Java is a straightforward sorting algorithm that compares neighboring elements and swaps them if they are in the incorrect order, progressively moving larger elements toward the end of the array.
3. What is the selection sort program in C?
The selection sort program in C is a C language implementation of the selection sort algorithm, which sorts an array by repeatedly finding the minimum element and placing it in its correct position.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...