Skip to content

Instantly share code, notes, and snippets.

@deniskyashif
Created July 26, 2015 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deniskyashif/e14a28e7ec52d9f8cd2b to your computer and use it in GitHub Desktop.
Save deniskyashif/e14a28e7ec52d9f8cd2b to your computer and use it in GitHub Desktop.
randomized selection in C#
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