Wednesday 13 July 2016

Selection Sort

Selection sort is a simple sorting algorithm.Smallest element is selected from the unsorted array and swapped with the leftmost element and that element becomes part of sorted array. This process continues moving unsorted array boundary by one element to the right.

 This algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2) where n are no. of items.

Following  program shows selection sort algorithm in JAVA.

Selection Sort : 
public class SelectionSort {

    public static void main(String args[]) {
        int array[] = { 5, 2, 7, 4, 9, 0 };
        array = selectionSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }

    private static int[] selectionSort(int array[]) {
        for (int i = 0; i < array.length; i++) {
            for (int j = i; j < array.length; j++) {
                if (array[i] > array[j]) {
                    int temp;
                    temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;

                }
            }
        }
        return array;
    }

}

No comments:

Post a Comment