Skip to content

Instantly share code, notes, and snippets.

@bgourlie
Last active August 29, 2015 14:17
Show Gist options
  • Save bgourlie/e2c70f47112dd36efb1e to your computer and use it in GitHub Desktop.
Save bgourlie/e2c70f47112dd36efb1e to your computer and use it in GitHub Desktop.
Partition around in a pivot in O(N) time and memory
using System;
using System.Linq;
class Something
{
public static void Main(string[] args)
{
var blah = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
PrintArray(blah);
Partition(blah, 9);
PrintArray(blah);
}
static void PrintArray(int[] arr)
{
foreach(var elem in arr)
{
Console.Write(elem + " ");
}
Console.WriteLine();
}
static void Partition(int[] arr, int pivotIdx)
{
var pivotValue = arr[pivotIdx];
Console.WriteLine("Pivoting on {0}", pivotValue);
int tmp;
// swap pivot to arr[0]
if(pivotIdx > 0){
tmp = arr[0];
arr[0] = pivotValue;
arr[pivotIdx] = tmp;
}
int j = 1;
for(int i = 1; i < arr.Length; i++)
{
if(arr[i] < pivotValue){
// if it's already in the correct location, no need to swap
if(i != j)
{
tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
j += 1;
}
}
// swap the pivot into the correct location
arr[0] = arr[j - 1];
arr[j - 1] = pivotValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment