Created
July 26, 2015 07:31
-
-
Save deniskyashif/e14a28e7ec52d9f8cd2b to your computer and use it in GitHub Desktop.
randomized selection in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
public class RSelect<T> where T : IComparable { | |
private Random rnd = new Random(); | |
public T Select(IList<T> collection, int left, int right, int k) { | |
if((right - left) <= 1) | |
return collection[right]; | |
int pivotIndex = this.Partition(collection, left, right, rnd.Next(left, right + 1)); | |
if(k > pivotIndex) | |
return this.Select(collection, pivotIndex, right, k); | |
else if(k < pivotIndex) | |
return this.Select(collection, left, pivotIndex - 1, k); | |
return collection[k]; | |
} | |
private int Partition(IList<T> collection, int left, int right, int pivotIndex) { | |
T pivot = collection[right]; | |
Swap(collection, right, pivotIndex); | |
pivotIndex = left; | |
for (int i = left; i < right; i++) { | |
if(collection[i].CompareTo(pivot) < 0){ | |
Swap(collection, i, pivotIndex); | |
pivotIndex++; | |
} | |
} | |
collection[right] = collection[pivotIndex]; | |
collection[pivotIndex] = pivot; | |
return pivotIndex; | |
} | |
private static void Swap(IList<T> collection, int first, int second) { | |
T temp = collection[first]; | |
collection[first] = collection[second]; | |
collection[second] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment