I have a question for a c++ lab assignment I have. The task is to implement some function for adding values, remove values from an array and so on. I have done most of it now, however I have some problem with the insert function. The assignment requires me to insert float values to this array without using any algorithm to sort it after each insert. I may not use anything from STL either. It will assume that I insert every value in sorted position immediately
So I wonder if someone could give me any clue how this problem can be solved?
EDIT
This assignment I am not going to implement it with linked list. It will be for my next assignement.
I have tried to write a insert function according to your pseudo code. I did not get it correctly though. Here’s the code anyway.
void array_insert(data_t list[], int& space_used, data_t value)
{
if(space_used == 0)
{
list[space_used] = value;
}
else
{
for(int i = space_used+1; i >= 0; i--)
{
if(value > list[i])
{
list[i+1] = value;
break;
}
else
{
list[i+1] = list[i];
}
if(i == 0)
{
list[i] = value;
}
}
}
space_used++;
}
finally finished, here’s the complete code. Thanks for the help from Mark and Casablanca
You have to shift all elements to make room for the new element. This is an O(n) operation. Since you can’t do better than O(n) I think it is reasonable to use this simple O(n) algorithm:
This assumes that your array has space to insert an extra element.