Page 1 of 1

Array sorting?

PostPosted: Thu May 23, 2013 6:29 pm
by Lacotemale
Hi all,

Im looking to sort my array if I remove an item, how is this best done?

Here is my awful code so far:

Code: Select all
void sortInventory()
{
    int i;
    for(i=0;i<50;i++)
    {
       if(inventory[0][i]==0 && inventory[0][i+1]>0)
        {
          inventory[0][i+1]=inventory[0][i-1];
        }
    }
}


Logic:

If an item is 0 but the next array value is greater than 0(contains an item)

Move the value ahead back to the current value. Does this make sense? I just want to push up the array when an item is removed. :D

Re: Array sorting?

PostPosted: Thu May 23, 2013 8:36 pm
by skydereign
Do you actually want to sort your array? It sounds like all you need is to fill in the gap whenever you remove an item. Sorting implies you have some key value to compare from. If you are sorting by two values (it exists or it doesn't exist) you don't really need to sort it. One easy way to handle this is when you remove an item, fine the last valid item in the array, and place it in the newly open position.

Re: Array sorting?

PostPosted: Thu May 23, 2013 9:09 pm
by Lacotemale
The easy way sounds good but kinda confusing to the user. "Lets use the item I collected last on my list, oh where did it go?"

I was thinking of just shifting the position of everything up once. So the item at position 4 would move to position 3 etc. :)

Does my code look alright for doing that?

Re: Array sorting?

PostPosted: Thu May 23, 2013 10:25 pm
by skydereign
Lacotemale wrote:I was thinking of just shifting the position of everything up once. So the item at position 4 would move to position 3 etc. :)

Does my code look alright for doing that?

No, because it addresses three items. You only want to address two. Also, you want to actually swap the values, that way the 0 gets passed back. If you don't do this, you'll either duplicate an item to fill the first whole, and that is it. Another thing, your code will go out of bounds, unless you have 51 items.
void sortInventory()
{
int i;
for(i=0;i<49;i++) // set to 49 to prevent the out of bounds
{
if(inventory[0][i]==0 && inventory[0][i+1]>0)
{
inventory[0][i]=inventory[0][i+1];
inventory[0][i+1] = 0;
}
}
}

Re: Array sorting?

PostPosted: Fri May 24, 2013 10:46 am
by Lacotemale
Ahhh my code was similar to this before until I went messing with it further. I was getting an error which I couldn't solve but this appears to be the important part:

Code: Select all
for(i=0;i<49;i++) // set to 49 to prevent the out of bounds


Thanks again Sky! :)