Name: Anonymous 2009-03-17 10:36
I need to use binary search to insert an item into a sorted list.
Here is my code which is not sorting the items correctly.
template<class ItemType> void SortedList<ItemType>::InsertItem(ItemType x)
{
int location = 0;
int end = length-1;
bool moreToSearch;
moreToSearch = (location<length);
while(moreToSearch)
{
int midPoint = (location + end) / 2;
if(x>values[midPoint])
{
location = midPoint + 1;
moreToSearch = (location<end);
}
else if(x<values[midPoint])
{
end = midPoint -1;
moreToSearch = (location<end);
}
else
{
moreToSearch = false;
location = midPoint;
break;
}
}
for(int index=length;index>location;index--)
values[index] = values[index-1];
values[location]=x;
length++;
}
What's wrong?
Here is my code which is not sorting the items correctly.
template<class ItemType> void SortedList<ItemType>::InsertItem(ItemType x)
{
int location = 0;
int end = length-1;
bool moreToSearch;
moreToSearch = (location<length);
while(moreToSearch)
{
int midPoint = (location + end) / 2;
if(x>values[midPoint])
{
location = midPoint + 1;
moreToSearch = (location<end);
}
else if(x<values[midPoint])
{
end = midPoint -1;
moreToSearch = (location<end);
}
else
{
moreToSearch = false;
location = midPoint;
break;
}
}
for(int index=length;index>location;index--)
values[index] = values[index-1];
values[location]=x;
length++;
}
What's wrong?