-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
executable file
·30 lines (24 loc) · 905 Bytes
/
Copy pathSelectionSort.java
File metadata and controls
executable file
·30 lines (24 loc) · 905 Bytes
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
package com.codeWithArsalon.Algorithms;
public class SelectionSort {
//ascending order
//we select the minimum value (from unsorted part)
//swap minValueIndexUnsorted with nextIndexSorted (next index in sorted part).
//O(n) - swapping
//O(n) - passes
//O(n) * O(n) = quadratic time complexity!
public void sort(int[] array) {
for (var i = 0; i < array.length; i++) {
var minIndex = i;
for (var j = i; j < array.length; j++) //start search after previous min item
if (array[j] < array[minIndex]) {
minIndex = j;
swap(array, minIndex, i);
}
}
}
private void swap(int[] array, int newMinIndex, int oldMinIndex) {
var selection = array[newMinIndex];
array[newMinIndex] = array[oldMinIndex];
array[oldMinIndex] = selection;
}
}