Wednesday 31 August 2016

Selection Sort


The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning of an array.

How Selection Sorting Works




/*
 * Created by Ali on 8/31/2016. 
 * Selection Sort 
 */
public class SelectionSort {

    public static void main(String str[]){

        int[] arr = new int[]{10,54,2,100,200,121,99,150,51,181};
        SelectionSort obj = new SelectionSort();
        int[] sortedArray = obj.selectionSort(arr);
        for (int i = 0; i < sortedArray.length; i++) {
            System.out.print(sortedArray[i] + " ");
        }
    }

    private int[] selectionSort(int[] unsortedArray) {
        int minIndex=0, temp=0;
        for(int i=0;i<unsortedArray.length;i++){
            minIndex = i;
            for(int j=i+1; j<unsortedArray.length; j++){
                if(unsortedArray[j] < unsortedArray[minIndex]){
                    minIndex = j;
                }
            }
            if(minIndex != i){
                temp = unsortedArray[minIndex];
                unsortedArray[minIndex] = unsortedArray[i];
                unsortedArray[i] = temp;
            }
        }
        return unsortedArray;
    }
}

Time Complexity: O(n*n) as there are two nested loops.

Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.

No comments:

Post a Comment