I've wrote this simple piece of code. And I have a slight problem with it.
int [] x = [50,70,10,12,129];
sort(x, 0,1);
sort(x, 1,2);
sort(x, 2,3);
sort(x, 3,4);
for(int i = 0; i < 5; i++)
Console.WriteLine(x[i]);
static int [] sort(int [] x, int i, int j)
{
if(j ==x.length)
return x;
else if(x[i]>x[j])
{
int temp = x[i];
x[i] = x[j];
x[j] = temp;
return sort(x, i, j+1);
}
else
return sort(x, i, j+1);
}
I feel that calling sort 4 time isn't the best soultion. I need a way to handle this using sort() also. I also ask you for your advice, suggestion, or tip. Thanks
Nothing wrong with wanting to learn - couple of obvious things.
Firstly you're already aware that there's a length property for the array - so you could use that to create a loop that gets rid of the multiple calls to sort at the start and makes the length of the array a non problem.
Secondly you might want to think about the way the sort works - how about this: you're attempting to bubble a value up to its correct place in the list (or down if you prefer!) - so for a list of n items, remove the first, sort the remaining n - 1 items (that's the recursive bit) then bubble the first item into place.
Been decades since I thought about this, fun!
Firstly, your sort is restricted to ints, however you can use the
IComparable<T>
interface to extend it to any comparable type. Alternatively you could have another parameter for aComparer<T>
to allow the user to define how to compare items in the input.A recursive bubble sort would probably look something like this: (NOTE: not tested...)
However, an iterative solution would probably be more efficient and easier to understand...
A simple bubblesort shouldn't need recursion. You could do something like this, just passing in the array to sort:
another one with only 2 params :p yeah :
Note : This is completly useless in real life because - its extremely slow - its recursion iteration is linear meaning that when you have more than 1k items, it will stackoverflow