forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort.java
49 lines (43 loc) · 1.13 KB
/
SelectionSort.java
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
48
49
/**
* Selection sort implementation
*
* <p>Run with:
*
* <p>$ ./gradlew run -Palgorithm=sorting.SelectionSort
*
* @author William Fiset, [email protected]
*/
package com.williamfiset.algorithms.sorting;
public class SelectionSort implements InplaceSort {
@Override
public void sort(int[] values) {
SelectionSort.selectionSort(values);
}
public static void selectionSort(int[] array) {
if (array == null) return;
final int N = array.length;
for (int i = 0; i < N; i++) {
// Find the index beyond i with a lower value than i
int swapIndex = i;
for (int j = i + 1; j < N; j++) {
if (array[j] < array[swapIndex]) {
swapIndex = j;
}
}
swap(array, i, swapIndex);
}
}
private static void swap(int[] ar, int i, int j) {
int tmp = ar[i];
ar[i] = ar[j];
ar[j] = tmp;
}
public static void main(String[] args) {
InplaceSort sorter = new SelectionSort();
int[] array = {10, 4, 6, 8, 13, 2, 3};
sorter.sort(array);
// Prints:
// [2, 3, 4, 6, 8, 10, 13]
System.out.println(java.util.Arrays.toString(array));
}
}