-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
41 lines (34 loc) · 1.02 KB
/
SelectionSort.java
File metadata and controls
41 lines (34 loc) · 1.02 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
package SortAlgorithms;
import java.util.Arrays;
public class SelectionSort {
public static void main(String... args) {
int[] intArray = {35, 45, -50, 12, 18};
for (int lastUnsortedIndex = intArray.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
int largest = 0;
for (int i = 1; i <= lastUnsortedIndex; i++) {
if (intArray[i] > intArray[largest]) {
largest = i;
}
swap(intArray, largest, lastUnsortedIndex);
}
}
System.out.println(Arrays.toString(intArray));
}
/**
* O(n²) because is into two loops
*
* @param array general array
* @param i largest index
* @param j lastUnsorted intex
*/
public static void swap(int[] array, int i, int j) {
if (i == j) {
//You shouldn't swap it
return;
}
//Swapping
int temp = array[i]; // O(n)
array[i] = array[j];
array[j] = temp;
}
}