C# quickSort with random pivot
I am trying to modify the heapSort algorithm into version with random pivot , and I dont know what to do.
Could any one help me ?
This is the code:
//QuickSort w C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickSort
{
class Program
{
//Zamienia miejscami , zwykły swap
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
//Procedura qiucksort
static void qsort(int[] tab, int left, int right)
{
if (left < right)
{
int m = left;
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)
{
int[] a = { 0, 12, 34, 9, 54, 12, 77, -3, -20 };
int i;
int left = 0;
int right = 8;
Console.WriteLine("Data before sort ");
for (i = 0; i < a.Length; i++)
Con开发者_如何转开发sole.Write(" {0} ", a[i]);
Console.WriteLine();
//Wywołanie procedury qsort
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();
}
}
}
This is changed code with random pivot , this code crashes at: Swap(ref tab[++m], ref tab[i]);
//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(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();
}
}
}
Your current pivot is the first element, you select it with
int m = left;
To use a random pivot, first
- select a random index p in the range [left, right] ,
- swap tab[left] and tab[p]
Because otherwise you would have to change your split algorithm (which is inline unfortunately) drastically.
But
A random pivot is far from ideal. If this is halfway serious, consider a median-of-three pivot
精彩评论