Skip to content

Instantly share code, notes, and snippets.

Created October 31, 2010 11:13
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 anonymous/656452 to your computer and use it in GitHub Desktop.
Save anonymous/656452 to your computer and use it in GitHub Desktop.
//QuickSort in C# with random pivot
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickSort
{
class Program
{
//common Swap function
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
//qiucksort procedure
static void qsort(int[] tab, int left, int right)
{
if (left < right)
{
System.Random myRandom = new System.Random(); //Creating instance of random variable
int m = myRandom.Next(left, right); //pivot = random number between left a right
Swap(ref tab[left],ref tab[m]);
for (int i = left + 1; i <= right; i++)
if (tab[i] < tab[left])
Swap(ref tab[++m], ref tab[i]);
Swap(ref tab[left], ref tab[m]);
qsort(tab, left, m - 1);
qsort(tab, m + 1, right);
}
}
static void Main(string[] args)
{
Console.Title = "QuickSort";
int[] a = { 0, 12, 34, 9, 54, 12, 77, -3};
int i;
int left = 0;
int right = 7;
Console.WriteLine("Data before sort ");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.WriteLine();
//call quicksort procedure
qsort(a, left, right);
Console.WriteLine("Data after sort");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.WriteLine();
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment