Created
April 23, 2014 23:59
-
-
Save skharel/11236705 to your computer and use it in GitHub Desktop.
Selection sort using java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* This code is written for Selection sort tutorial | |
* The comment won't make sense unless you read the slide that goes with it | |
* | |
* Go to Vumari.com to find the slides | |
* | |
*/ | |
public class SelectionSort { | |
private int[] array; | |
public SelectionSort(int[] array){ | |
this.array = array; | |
} | |
public void sort(){ | |
for (int startingIndex = 0; startingIndex < (array.length - 1); startingIndex++) { | |
int smallestIndex = startingIndex; //assumption | |
for (int j = startingIndex + 1; j < array.length; j++) {//start from index next to startingIndex | |
if(array[j] < array[smallestIndex]){// validate the assumption | |
smallestIndex = j; // make new assumption if old was wrong | |
} | |
} | |
//swap | |
if(startingIndex != smallestIndex) swap(startingIndex, smallestIndex); | |
} | |
} | |
private void swap(int startingIndex, int smallestIndex){ | |
int temp = array[startingIndex]; | |
array[startingIndex] = array[smallestIndex]; | |
array[smallestIndex] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment