In-place sorting
Complexity: O(n^2)
/** To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package careercup.google;
<div id="_mcePaste">/**
*
* @author Harit
*/
public class SelectionSort {
//private static int[] input = new int[]{5,1,4,2,8};
private static int[] input = new int[]{9,8,7,4,5,6,3,2,1};
public static void main(String args[]){
int last_index = 0;
int swap_index = -1;
printArray();
for(int i=1; i<input.length; i++){
swap_index = returnIndex(i);
if(input[last_index] <= input[swap_index]){
continue;
}
int temp = input[last_index];
input[last_index] = input[swap_index];
input[swap_index] = temp;
last_index += 1;
}
printArray();
}
private static int returnIndex(int index){
int rindex = index;
int smallest = input[index];
for(int i=index+1; i<input.length; i++){
if(input[i] < smallest){
rindex = i;
smallest = input[i];
}
}
return rindex;
}
private static void printArray(){
for(int j=0; j<input.length; j++){
System.out.print(input[j] + " ");
}
System.out.println("");
}
}
Output:
run:
9 8 7 4 5 6 3 2 1
1 2 3 4 5 6 7 8 9
BUILD SUCCESSFUL (total time: 0 seconds)
