Skip to content

Instantly share code, notes, and snippets.

@skharel
Created April 23, 2014 23:59
Show Gist options
  • Save skharel/11236705 to your computer and use it in GitHub Desktop.
Save skharel/11236705 to your computer and use it in GitHub Desktop.
Selection sort using java
/*
*
* 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