I'm relatively young in Java, and am familiar with only the basics of the language, yet. I've started studying data structures, and I've made an attempt to create a solution for the selection sort algorithm. After many attempts with errors and exceptions, I've managed to come up with what looks like a working solution.
I realize that having the swap implemented as a separate method call in the sort function causes some additional overhead, instead of having the swap directly in the loop. But this version helps me follow along the logic clearly, as I'm not that experienced yet.
package Chap_3; /** * Created by user1 on 8/7/15. * my selection sort version */ class MySelSort { //reference to array private int[] arr; //num. of elements private int n; //constructor public MySelSort(int max) { //create array with size arr = new int[max]; //set current items to 0 n = 0; } //-------------------------------------------------- //insert() public void insert(int key) { //insert key to relevant place in array arr[n] = key; //increase size of array n++; } //-------------------------------------------------- //display() public void display() { System.out.println("The items in the array are: "); for(int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } //------------------------------------------------- //sort() using selection sort public void selSort() { int in, out; //int min = 0; for(out = 0; out < n - 1; out++) { int min = out; for(in = out+1; in < n; in++) { if(arr[min] > arr[in]) { min = in; } } if(arr[out] > arr[min]) { swap(out, min); } } } //------------------------------------------------ //swap() public void swap(int one, int two) { int temp = arr[one]; arr[one] = arr[two]; arr[two] = temp; } } public class MySelSortApp { public static void main(String[] args) { //create array MySelSort sel = new MySelSort(100); //insert 8 items sel.insert(40); sel.insert(60); sel.insert(90); sel.insert(10); sel.insert(80); sel.insert(70); sel.insert(20); sel.insert(50); //display items sel.display(); //sort items sel.selSort(); //display again sel.display(); } }
max
item). So I would make a check to verify that this does not happen. In addition I'm sure you are aware that there are other structures which could have handled the list for you, but it it is good training to do it from scratch a few times in the beginning. Code looks tidy in other aspects. Do remove void comments like// insert()
\$\endgroup\$