Selection Sort Algorithm.

Selection Sort Algorithm:
Selection Sort is one of the frequently used sorting algorithm to sort elements. In this sorting algorithm, firstly it will find a minimum value and then swap that value with position of first value. Similarly, then it will find the second smallest element and  swap it with element at second value. Same process is repeated until Array gets sorted. 

Algorithm:
  1. Loop i will start from 0 and it will be executed until i < n-1. //This loop is for passes.
  2. Set min = i
  3. Second Loop of j , j will be always one step forward to i and it will go until j < n.
  4. When, if condition turns true then we will update value of min. i.e min = j
  5. At last when second loop turns false then swapping of arr[min] and arr[i] will be done.
  6. Same steps will be repeated until we get Sorted Array. (Refer Code).
Image Illustration:

Code Implementation:
public class SelectionSort {
    public static void main(String[] args) {
        int[] arr = { 1050129321243 };
        selectionSort(arrarr.length);
        System.out.print("Sorted Arrays: ");
        displayArray(arr);
    }

    public static void selectionSort(int[] arrint n) {
        for (int i = 0i < n - 1i++) {
            int min = i;
            for (int j = i + 1j < nj++) {
                if (arr[j] < arr[min]) {
                    min = j// will update min
                }
            }
            // swapping of arr[min] and arr[i]
            int temp;
            temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
    }

    public static void displayArray(int[] arr) {
        for (int value : arr) {
     System.out.print(value + " ");
        }
    }
}
 

Output:
Sorted Arrays: 1 10 12 29 32 43 50

Complexity Analysis:

Time Complexity: The worst case complexity of this sorting algorithm is O(n2).
Space Complexity: O(1) because no extra space is used.

Previous Post Next Post

Contact Form