- Selection sort algorithm is to arrange unsorted elements in to sorting order with increasing or decreasing order.
- To sort list of unsorted list of elements first it will search for minimum value in the list and place it in first index.
- Now first place is fixed with smallest value in the list now it starts from second element and compare next element and if it is big it compares next element if it is small it picks that element and compares with next element.
- So again it picks smallest element in the list and place it in second place. This procedure will repeat until it reaches n-1 position.
Time complexity of selection sort algorithm:
1.Best case time complexity: O(n2)
2.Average case time complexity: O (n2)
3.Worst case time complexity: O (n2)
Program #1: Write a Java example program to sort unsorted elements in ascending order using selection sort algorithm
- package com.java.sortingalgorithms;
- public class SelectionSortInJava {
- public static int[] selectionSortArray(int[] array){
- for (int i = 0; i < array.length - 1; i++)
- {
- int index = i;
- for (int j = i + 1; j < array.length; j++)
- if (array[j] < array[index])
- index = j;
- int minimumNumber = array[index];
- array[index] = array[i];
- array[i] = minimumNumber;
- }
- return array;
- }
- public static void main(String a[]){
- int[] array = {12,24,6,56,3,9,15,41};
- System.out.println("Before sorting");
- for(int i:array){
- System.out.print(i);
- System.out.print(", ");
- }
- int[] resultarr = selectionSortArray(array);
- System.out.println("\nAfter sorting");
- for(int i:resultarr){
- System.out.print(i);
- System.out.print(", ");
- }
- }
- }
Output:
- Before sorting
- 12, 24, 6, 56, 3, 9, 15, 41,
- After sorting
- 3, 6, 9, 12, 15, 24, 41, 56,
Implementation of Selection Sort algorithm
No comments