Selection Sort program


class SelectionSort {
    private static int[] array;
    
    private void sort() {
        for(int i = 0; i < array.length; i++) { 
            int minIndex = i;
            for(int j = i+1; j < array.length; j++) {
                if(less(j, minIndex)) {
                    minIndex = j;   
                }
            }
            swap(i, minIndex);
        }
    }
    
    private void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    
    private boolean less(int i, int j) {
        return array[i] < array[j];
    }
    
    private void display() {
        for(int key : array) {
            System.out.print(key + " ");
        }
    }
    
	public static void main (String[] args) {
	    SelectionSort obj = new SelectionSort();
		array = new int[] {11,13,7,12,16,9,24,5,10,3};
		System.out.println("Unsorted array : ");
		obj.display();
		
		obj.sort();
		System.out.println("\nSorted array : ");
		obj.display();
	}
}


Output
Unsorted array : 
11 13 7 12 16 9 24 5 10 3 
Sorted array : 
3 5 7 9 10 11 12 13 16 24 

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance