Sorting is a technique for organizing the elements in an increasing or decreasing order. Similarly, the Selection sort algorithm is one of the techniques to achieve the ordering of elements in an array in an increasing or decreasing order in a program.
Selection Sort Algorithm
The selection sort is a simple sorting algorithm which is an in-place comparison-based algorithm. It has two parts where the left end has a sorted part and the right end has an unsorted part.
In the beginning, the left end is empty and the right end has all the elements then the smallest element from the right end is brought to the left end and swapped with the leftmost element. This process continues until the element from the right end is brought to the left by swapping.
Although, it may cause a problem with the large inputs.
C# Program for Selection Sort
There is an unsorted list of arrays given in a program. With the help of selection sort, we sort those array lists in ascending order.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | //selection sort using System; public class Sort { static void Main(string[] arg) { int temp, smallest; int[] array = new int[10] { 45, 67, 2, 998, 1, 33, 27, 7, 90, 11 }; Console.WriteLine("Selection sort in C#"); Console.Write("Unsorted Array are: "); for (int i = 0; i < array.Length; i++) Console.Write(array[i] + " "); for (int i = 0; i < array.Length - 1; i++) { smallest = i; for (int j = i + 1; j < array.Length; j++) { if (array[j] < array[smallest]) smallest = j; } temp = array[smallest]; array[smallest] = array[i]; array[i] = temp; } Console.WriteLine(); Console.Write("After Selection sort: "); for (int i = 0; i < array.Length; i++) Console.Write(array[i] + " "); } } |
The Output of Selection Sort program in C#.
Time Complexity of Selection Sort:
- Best case:
0(n^2)
- Average case:
0(n^2)
- Worst case:
0(n^2)