find the kth smallest number in a list in csharp

One way to find the kth smallest number in a list is to sort the list and then return the kth element. This can be done efficiently using the QuickSelect algorithm. The QuickSelect algorithm is similar to the QuickSort algorithm, but instead of sorting the entire list, it only partitions the list around a randomly chosen pivot element until it finds the kth smallest element.

Here's an implementation of the QuickSelect algorithm in C#:

main.cs
public static int QuickSelect(int[] arr, int k)
{
    int left = 0, right = arr.Length - 1;

    while (true)
    {
        if (left == right)
            return arr[left];

        int pivotIndex = Partition(arr, left, right);
        if (k == pivotIndex)
            return arr[k];
        else if (k < pivotIndex)
            right = pivotIndex - 1;
        else
            left = pivotIndex + 1;
    }
}

private static int Partition(int[] arr, int left, int right)
{
    int pivotIndex = new Random().Next(left, right);
    int pivotValue = arr[pivotIndex];

    Swap(arr, pivotIndex, right);
    int storeIndex = left;

    for (int i = left; i < right; i++)
    {
        if (arr[i] < pivotValue)
        {
            Swap(arr, i, storeIndex);
            storeIndex++;
        }
    }

    Swap(arr, storeIndex, right);
    return storeIndex;
}

private static void Swap(int[] arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
973 chars
47 lines

To use this function, simply pass in the list of numbers as an array and the value of k:

main.cs
int[] arr = { 5, 2, 4, 1, 3 };
int k = 2;
int kthSmallest = QuickSelect(arr, k - 1);  // subtract 1 because we're zero-indexed

Console.WriteLine(kthSmallest);  // output: 2
174 chars
6 lines

gistlibby LogSnag