forked from CodersForLife/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
47 lines (45 loc) · 1.11 KB
/
Copy pathSelectionSort.java
File metadata and controls
47 lines (45 loc) · 1.11 KB
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
/**
* Utility class for sorting an array using Selection Sort algorithm. Selection
* Sort is a basic algorithm for sorting with O(n^2) time complexity. Basic idea
* of this algorithm is to find a local minimum, which is the minimum value from
* (i+1) to length of the array [i+1, arr.length), and swap it with the current
* working index (i).
*
* @author Kongpon Charanwattanakit
*
*/
public class SelectionSort {
/**
* Sort an array using Selection Sort algorithm.
*
* @param arr
* is an array to be sorted
*/
public static void sort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
/* find local min */
if (arr[j] < arr[min]) {
min = j;
}
}
swap(arr, i, min);
}
}
/**
* Utility method for swapping elements in an array.
*
* @param arr
* is an array to be swapped
* @param i
* is index of first element
* @param j
* is index of second element
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}