I have defined the folloing method to sort an array:
public int[] BubbleSort(int[] ints)
{
for (int i = 0; i < ints.Length; i++)
{
if (ints[i] > ints[i + 1])
{
int tempValue = ints[i];
ints[i] = ints[i + 1];
ints[i + 1] = tempValue;
}
}
return ints;
}
However, my implementation above is throwing System.IndexOutOfRangeException : Index was outside the bounds of the array. What might be the problem?
Go to
.Length - 1instead. Also, with bubble sort, you need to iterate over the array until no more elements should be swapped (this is what makes bubble sort so inefficient):