Medium csharp

Selection sort

Problem

Implement selection sort on {64,25,12,22,11}.

Hints
  • Track index of minimum element from i to end.

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

class Program
{
    static void Main()
    {
        int[] arr = { 64, 25, 12, 22, 11 };
        for (int i = 0; i < arr.Length - 1; i++)
        {
            int minIdx = i;
            for (int j = i + 1; j < arr.Length; j++)
                if (arr[j] < arr[minIdx]) minIdx = j;
            (arr[i], arr[minIdx]) = (arr[minIdx], arr[i]);
        }
        Console.WriteLine(string.Join(", ", arr));
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Find minimum in unsorted portion and swap to front each pass.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details