Here's the question at hand: You have a set of N random numbers to be inserted into a sorted List (smallest to largest). What would be the worst-case asymptotic time performance for building the entire list?
I know how to insert a sorted list in code in a few languages (I know there's a couple different ways): I have the program check that there is still room in the array for one more item. Then, to insert the item into the list, all the items in the list that are larger than the one to be inserted are moved to the right via a for loop. Then I have a pointer to the item to be inserted is recorded in the appropriate array position. In C++:
void SortedListAsArray::Insert (Object& object)
{
if (count == array.Length ())
throw domain_error ("list is full");
unsigned int i = count;
while (i > 0 && *array [i - 1U] > object)
{
array[i] = array [i - 1U];
--i;
}
array[i] = &object;
++count;
}
This is O(n) time I think. What confuses me is the whole "building" the entire list part. I'm not sure if it means building a list from scratch given those numbers and inserting them then sorting, or just inserting the set of numbers into an already sorted list. What do you guys think it means and would it change my run time either way? Thanks!
Figured it out. It would be O(n^2) if I did it a different way (and easier) using two for loops. I'm assuming that there is already a sorted list, and I'm just using an insertion sort to insert the numbers into it.