03 Jul

C# Selection Sort Algorithm Implementation

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It selects the smallest unsorted item remaining in the list. Then swapping it with the item in the next position to be filled.

For more information about Selection Sort Algorithm:
http://en.wikipedia.org/wiki/Selection_sort

Implementation and Usage:

            int[] arr = new int[10]
            {
                1, 5, 4, 11, 20, 8, 2, 98, 90, 16
            };

            Sort(arr);
            Console.WriteLine("Sorted Values:");
            for (int i = 0; i < arr.Length; i++)
                Console.WriteLine(arr[i]);

            //Output:
            //Sorted Values:
            //1
            //2
            //4
            //5
            //8
            //11
            //16
            //20
            //90
            //98
        private void Sort(int[] arr)
        {
            int i, j, min;
            for (i = 0; i < arr.Length; i++)
            {
                min = i;
                for (j = 0; j < arr.Length; j++)
                {
                    if (arr[j] > arr[min])
                    {
                        min = j;
                        Swap(ref arr[i], ref arr[min]);
                    }
                }
            }
        }

        private void Swap(ref int x, ref int y) 
        {
            int temp = x; 
            x = y;
            y = temp;
        }

See Also:

3 thoughts on “C# Selection Sort Algorithm Implementation

  1. Pingback: C# Insertion Sort Algorithm Implementation | C# Examples

  2. Pingback: C# Bubble Sort Algorithm Implementation | C# Examples

  3. Pingback: All Useful Sorting Algorithms | C# Examples

Leave a Reply

Your email address will not be published. Required fields are marked *