Week 27 Hacks
public class Number {
private int value;
public Number(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class selectionSort {
public static void main(String args[]) {
Number[] num = new Number[9];
num[0] = new Number(98);
num[1] = new Number(87);
num[2] = new Number(72);
num[3] = new Number(66);
num[4] = new Number(52);
num[5] = new Number(51);
num[6] = new Number(36);
num[7] = new Number(29);
num[8] = new Number(13);
for (int i = 0; i < num.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < num.length; j++) {
if (num[j].getValue() < num[minIndex].getValue()) {
minIndex = j;
}
}
// swap the numbers at i and minIndex
Number temp = num[i];
num[i] = num[minIndex];
num[minIndex] = temp;
}
// print sorted numbers
for (int i = 0; i < num.length; i++) {
System.out.println("Number " + (i+1) + " value: " + num[i].getValue());
}
}
}
selectionSort.main(null);
Big O Complexity of Selection Sort
The Big O complexity of a given algorithm is a calculation of how many steps this algorithm would take to complete in the worst-case scenario. To find the big O complexity of selection sort, the first step would be to set up the worst-case scenario, which would be a list of numbers ordered from biggest to smallest. Using a list of 9 numbers means that the first number is set as the minimum, and then each number after is also set as the new minimum. This would take 9 steps for one number. This means that the algorithm will take 81 steps total to complete in this worst-case scenario. Finally our big O notation would be determined as n^2, since the worst case scenario took the number of indexes^2 to complete.