How to implement selection sort in c#

In this post, I will show you how to implement selection sort in c#. Before going to implement selection sort, let’s describe how selection sort works.

  1. Go through the list one item at a time.
  2. Keep track of the smallest item found.
  3. Find the smallest item out and add it to a list of sorted items.
  4. Repeat until all the items have been sorted
class Program
    {
        // Selection Sort Algorithm
        public static void SelectionSort(int[] arr)
        {
            int i, j;
            int min;
            for (i = 0; i < arr.Length - 1; i++)
            {
                min = i;
                for (j = i + 1; j < arr.Length; j++)
                {
                    if (arr[j] < arr[min])
                    {
                        min = j;
                    }
                }
                Swap(arr, i, min);
            }
        }
        private static void Swap(int[] arr, int i, int min)
        {

            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        static void Main(string[] args)
        {

            int[] arr = new int[] { 1, 2, 0, -3, 32 };
            SelectionSort(arr);

        }


    }

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post