Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
47 lines (42 loc) · 1.21 KB

File metadata and controls

47 lines (42 loc) · 1.21 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package Sorts;
public class SelectionSort implements SortAlgorithm {
/**
* Generic selection sort algorithm in increasing order.
*
* @param arr the array to be sorted.
* @param <T> the class of array.
* @return sorted array.
*/
@Override
public <T extends Comparable<T>> T[] sort(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[minIndex].compareTo(arr[j]) > 0) {
minIndex = j;
}
}
if (minIndex != i) {
T temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
return arr;
}
/** Driver Code */
public static void main(String[] args) {
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
SelectionSort selectionSort = new SelectionSort();
Integer[] sorted = selectionSort.sort(arr);
for (int i = 0; i < sorted.length - 1; ++i) {
assert sorted[i] <= sorted[i + 1];
}
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = selectionSort.sort(strings);
for (int i = 0; i < sortedStrings.length - 1; ++i) {
assert strings[i].compareTo(strings[i + 1]) <= 0;
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.