Hello,
I just started working with Introduction to Algoriths from MIT Press
and my goal is to rewrite them in c#. This is just a learning
experiance.
The following code:
INSERTION-SORT(A)
for j ← 2 to length[A] // 1 Based Array
{
do key ← A[j]
i ← j - 1
while i 0 and A[i] key
{
do A[i + 1] ← A[i]
i ← i - 1
}
A[i + 1] ← key
}
Becomes:
for (int j = 1; j <= (length-1); j++) // 0 based array
{
uint CurrentCard=IntCard[j];
int i =j-1;
while ((i 0) & (IntCard[i] CurrentCard))
{
IntCard[i + 1] = IntCard[i];
i = i - 1;
}
IntCard[i+1]=CurrentCard;
After much head banging I realized the original Algorithm would also
fail in a 1 based array because at i=i-1 becomes 0 and there is no 0 in
the 1 based array.
My question is:
How do I check if the element exists before I run the while loop AND is
this the best way of doing this.Dont forget I dont want to use any
premade functions,I just want a simple algorithm.
Thanks
Mike