I'm trying to implement a quicksort algorithm to sort an array of floats. Whenever I reference an index in the array, i get this error:
Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast)?
Here's the algorithm:
class Quicksort
{
public static void Sort(float[] numbers, int left, int right)
{
float i = Convert.ToSingle(left);
float j = Convert.ToSingle(right);
var pivot = numbers[(left + right) / 2];
while (i <= j)
{
while (numbers[i] < pivot) //ERROR HERE
i++;
while (numbers[j] > pivot) //ERROR HERE
j--;
if (i <= j)
{
float tmp = numbers[i]; //ERROR HERE
numbers[i] = numbers[j]; //ERROR HERE
numbers[j] = tmp; //ERROR HERE
i++;
j--;
}
}
if (left < j)
Sort(numbers, left, j);
if (i < right)
Sort(numbers, i, right);
}
}
The conversion error appears whenever i use numbers[i]
or numbers[j]
How would I fix this?
Thanks
The problem is that you're trying to use floating point values for array indexes. That doesn't work: array indexes are always integers in C#, regardless of the type of the array element. That makes sense - there's no such thing as "element 1.3 of an array" for example.
Just change the first two lines of your method to:
int i = left;
int j = right;
... or remove i
and j
entirely, and use left
and right
throughout the method.