Algorithm question

A

AMP

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 > key
{
do A[i + 1] ↠A
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 > CurrentCard))
{
IntCard[i + 1] = IntCard;
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
 
C

Chris Dunaway

AMP said:
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 > key
{
do A[i + 1] ↠A
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 > CurrentCard))
{
IntCard[i + 1] = IntCard;
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.


When i = 0, the code will fall out of the loop and will not try to
process IntCard[0]. Incidentally in your while loop you should be
using && and not &. & is a bitwise operator. && is the logical and
operator.
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.

In C# when you declare an array of ints, each element is defaulted to 0
so unless you make 0 indicate an "empty" element, I know of no way to
do this. For reference types, you can check them for null.

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top