Selection Sort program in C#


Selection Sort is a sorting algorithm that finds the minimum value in the array for each iteration of the loop. Then this minimum value is swapped with the current array element. This procedure is followed until the array is sorted.

A program that demonstrates selection sort in C# is given as follows.

Example

 Live Demo

using System;
public class Example {
   static void Main(string[] args) {
      int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
      int n = 10;
      Console.WriteLine("Selection sort");
      Console.Write("Initial array is: ");
      for (int i = 0; i < n; i++) {
         Console.Write(arr[i] + " ");
      }
      int temp, smallest;
      for (int i = 0; i < n - 1; i++) {
         smallest = i;
         for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[smallest]) {
               smallest = j;
            }
         }
         temp = arr[smallest];
         arr[smallest] = arr[i];
         arr[i] = temp;
      }
      Console.WriteLine();
      Console.Write("Sorted array is: ");
      for (int i = 0; i < n; i++) {
         Console.Write(arr[i] + " ");
      }
   }
}

Output

The output of the above program is as follows.

Selection sort
Initial array is: 56 1 99 67 89 23 44 12 78 34
Sorted array is: 1 12 23 34 44 56 67 78 89 99

Now, let us understand the above program.

First the array is initialized and its value is printed using a for loop. This can be seen in the following code snippet.

int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}

A nested for loop is used for the actual sorting process. In each pass of the outer for loop, the smallest element in the array is found and replaced by the current element. This process continues until the array is sorted. This can be seen in the following code snippet.

for (int i = 0; i < n - 1; i++) {
   smallest = i;
   for (int j = i + 1; j < n; j++) {
      if (arr[j] < arr[smallest]) {
         smallest = j;
      }
   }
   temp = arr[smallest];
   arr[smallest] = arr[i];
   arr[i] = temp;
}

Finally the sorted array is displayed. This can be seen in the following code snippet.

Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}

Updated on: 26-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements