I am trying to Quicksort 10 random numbers within an listbox. But i cant use the method on my random iar, can anyone give me some advice.
Code behind button:
private void btnSort_Click(object sender, EventArgs e)
{
Random r = new Random();
int n = 10;
int[] iar = new int[n];
for (int i = 0; i < iar.Length; i++)
{
iar[i] = r.Next(0, 20);
lb1.Items.Add(iar[i]);
//here is the error i want to fill lb2 with the quicksorted array
// using the quicksort method
Quicksort(iar, 0, iar.Length - 1);
}
for (int i = 0; i < iar.Length; i++)
{
lb2.Items.Add(iar[i]);
}
}
Quicksort method
public static void Quicksort(IComparable[] elements, int left, int right)
{
int i = left, j = right;
IComparable pivot = elements[(left + right) / 2];
while (i <= j)
{
while (elements[i].CompareTo(pivot) < 0)
{
i++;
}
while (elements[j].CompareTo(pivot) > 0)
{
j--;
}
if (i <= j)
{
// Swap
IComparable tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
// Recursive calls
if (left < j)
{
Quicksort(elements, left, j);
}
if (i < right)
{
Quicksort(elements, i, right);
}
}
}
ERRORS:
Error 2 Argument 1: cannot convert from ‘int[]’ to ‘System.IComparable[]’
Error 1 The best overloaded method match for ‘Quicksort.FrmQuicksort.Quicksort(System.IComparable[], int, int)’ has some invalid arguments
Thanxs for looking:)
In the given context there is no real need to specify
IComparablerather thanintbecause you are only ever using integers. You’re also callingQuickSortas each number is generated when it will work best if you run theQuickSortalgorithm on the already generated list so move the statement outside the loop. Also bare in mind that there are better sorting algorithms for sorting tiny amounts of data like this.Click Event Handler:
QuickSort Function