I have a method which sorts items in an array which is handed to it.
Currently the method accepts an int[]
as an argument. The Swap()
method being called here just swaps the two indexes in the array handed as arguments.
I'm not interested in how to make a better sorting method here, just how to let it accept any array where that array contains comparable types.
Swap will also have to be updated to swap items in any type of array.
Here is what I currently have:
static void Swap(int firstIndex, int secondIndex, int[] array)
{
int firstValue = array[firstIndex];
int secondValue = array[secondIndex];
array[firstIndex] = secondValue;
array[secondIndex] = firstValue;
}
static void DoubleBubbleSort(int[] array)
{
for (int i = 0; i < array.Length -1; i++)
{
// if next index is smaller swap values
if (array[i + 1] < array[i])
{
Swap(i, i+1, array);
for (int j = i; j > 0; j--)
{
if (array[j] < array[j - 1])
{
Swap(j,j-1,array);
}
else
{
break;
}
}
}
}
}
I guess I need something a bit like this for the signature of the method
DoubleBubbleSort(Array<T>) where T : Icomparable<T>
However I can't get anything like that to work. Is what I'm asking for possible? If the sort method could sort an array of anything that's sortable it would have much more utility.
For swap I guess it could be:
static void Swap(int firstIndex, int secondIndex, object[] array)
{
var firstValue = array[firstIndex];
var secondValue = array[secondIndex];
array[firstIndex] = secondValue;
array[secondIndex] = firstValue;
}
But I'm not sure if this could work either.