Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphoarty/020d56061279717488c840aa868a4930 to your computer and use it in GitHub Desktop.
Save graphoarty/020d56061279717488c840aa868a4930 to your computer and use it in GitHub Desktop.
public class SelectionSort {
public static final int max = 10;
public static void main(String[] args){
int[] toSortArray = new int[max];
int min=999;
int minIndex = 0;
for(int i = 0; i < max; i++){
toSortArray[i] = (int) (Math.random()*100);
}
System.out.println("The array to be sorted is:");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
//beginning of the algorithm
//important to place the minimum as the first element!
for(int i = 0 ; i < max; i++){
min = 9999; //put a very big value here!
for(int j = i; j < max; j++){
if(min > toSortArray[j]){
min = toSortArray[j];
minIndex = j;
}
}
int temp;
temp = toSortArray[minIndex];
toSortArray[minIndex] = toSortArray[i];
toSortArray[i] = temp;
}
// End of the algorithm
System.out.println("The sorted array is: ");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment