Understanding key comparisons and item assignments for insertion sort algorithm
Aug 29, 2014 at 7:39pm UTC
Where in this algorithm are key comparisons and item assignments made?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
void insertionSort(int list3[], int listLength)
{
int temp;
int loc;
int firstOutOfOrder;
for (firstOutOfOrder=1; firstOutOfOrder<listLength; firstOutOfOrder++)
{
if (list3[firstOutOfOrder] < list3[firstOutOfOrder-1])
{
loc = firstOutOfOrder;
temp = list3[firstOutOfOrder];
do
{
list3[loc] = list3[loc-1];
loc--;
}
while (loc>0 && list3[loc-1]>temp);
list3[loc] = temp;
}
}
}
Aug 29, 2014 at 7:55pm UTC
Do you know what an assignment is?
Do you know what a comparison is?
If you do, you should have no difficulty pointing them out.
Aug 29, 2014 at 8:06pm UTC
I understand the bold line is a comparison. But what do i consider the italics line. is that still considered a comparison.
Item assignments are underlined.
Am I correct with all of above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
void insertionSort(int list3[], int listLength)
{
int temp;
int loc;
int firstOutOfOrder;
for (firstOutOfOrder=1; firstOutOfOrder<listLength; firstOutOfOrder++)
{
if (list3[firstOutOfOrder] < list3[firstOutOfOrder-1])
{
loc = firstOutOfOrder;
temp = list3[firstOutOfOrder];
do
{
list3[loc] = list3[loc-1];
loc--;
}
while (loc>0 && list3[loc-1]>temp );
list3[loc] = temp;
}
}
}
Aug 29, 2014 at 8:19pm UTC
Am I correct with all of above.
Yes. The italicized code is a key comparison.
Aug 29, 2014 at 8:26pm UTC
Thanks. And did I guessed the underlined ones correct. Are they still item assignments?
Aug 29, 2014 at 9:37pm UTC
Are they still item assignments?
Well, line 11 is not. Both of the variables in question are indexes, not items to be sorted.
Line 12 depends on the definition of "item assignments." If it is assignments to items in the list, then no,
temp is not in the list. If it is an assignment of one item to another, then yes.
Lines 15 and 21 are definitely item assignments.
Aug 29, 2014 at 10:45pm UTC
Thanks a lot. This extremely helps me.
Topic archived. No new replies allowed.