Selection Sort Sample Code
Learning the different types of data
public class Turtle {
private int height;
public Turtle(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
}
public class SelectionSortTurtles {
public static void main(String[] args) {
Turtle[] turtles = new Turtle[7];
turtles[0] = new Turtle(10);
turtles[1] = new Turtle(5);
turtles[2] = new Turtle(15);
turtles[3] = new Turtle(8);
turtles[4] = new Turtle(20);
turtles[5] = new Turtle(12);
turtles[6] = new Turtle(3);
// perform selection sort by height
for (int i = 0; i < turtles.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < turtles.length; j++) {
if (turtles[j].getHeight() < turtles[minIndex].getHeight()) {
minIndex = j;
}
}
// swap the turtles at i and minIndex
Turtle temp = turtles[i];
turtles[i] = turtles[minIndex];
turtles[minIndex] = temp;
}
// print the sorted turtles
for (int i = 0; i < turtles.length; i++) {
System.out.println("Turtle " + (i+1) + " height: " + turtles[i].getHeight());
}
}
}
SelectionSortTurtles.main(null);