2

This is the code I wrote for inputting random numbers initially and then sorting them with the insertion sort method.

        #include<iostream>

        #include <cstdlib>

        #include <ctime>

        using namespace std;

        int main(void)
        {

           int array[10];

           srand (time(0));

           for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// inputting values into array[10]
           {
              array[i] = 1 + (rand()%100); //any random number between 1 - 100
           }
           cout <<" Before sorting " << " ---" <<endl;
           for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// printing the values
           {
               cout  <<  array[i]<< endl;
           }


           int key ;
           int t;//for future purpose
           int compcount = 0;//to keep track of comparisons
           for (int j = 1; j<sizeof(array)/sizeof(array[0]);j++)
           {
               key = array[j];//assign to second element initially
               t = j-1;//assign to first element initially
               while (j > 0 && array[t]>key)
               {
                   array[t+1] = array[t];//moving array if bigger than next element
                   t = t-1;
                   compcount++;
               }
               array[t+1] = key;
           }
           cout << " After sorting" << " --- " <<endl;

           for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )
           {
               cout  <<  array[i]<< endl;
           }
           cout << "comparison count is " << compcount << endl;
           system ("pause");

           return 0;

        }

I'll be honest , I have a project and it asks to run the algorithm for the best , worst and random input and calculate the number of key comparisons (Which I believe is "compcount" in this code)

Now random input would make sense for this. When I did another code with "an already sorted "array of numbers (the best case scenario) ,the number of key comparisons was 0. Can someone shed some light onto whether the worst case scenario is just the complete opposite of that? If that were the case I tried doing that but I only got 32 comparisons with the size of the array being 32.

Sorry for the long question . Worst case input should have (n^2-n)/2 number of comparisons right? And the best case should have n-1 because only the first element would run through the entire list and confirm it being sorted.How do I get this in code?

user973511
  • 329
  • 3
  • 11
Mahi Vattekat
  • 87
  • 1
  • 2
  • 7
  • Who gave you that code? Have you tested it? The sorting part is definitely not correct. – Björn Pollex Nov 08 '11 at 14:25
  • It is.I wrote this code and ran it as well.It works just fine too. – Mahi Vattekat Nov 08 '11 at 14:27
  • 1
    No, it is not. See [here](http://ideone.com/OyNDm). – Björn Pollex Nov 08 '11 at 14:29
  • You should consider naming your variables better. What is the value of `j > 0` in your inner while loop? I don't see it ever getting messed with outside your for loop, which means it should always be true. – Mranz Nov 08 '11 at 14:31
  • I dont know what's wrong with your code but I ran mine and it works just fine. You dont have the int main(void) is a difference I see.I dont know if thats relevant. – Mahi Vattekat Nov 08 '11 at 14:32
  • @Mranz if you look closely it says j>0 "&&" array[t]> key.So as long as BOTH suffice the while loop will go on until the next iteration for the for loop – Mahi Vattekat Nov 08 '11 at 14:33
  • 2
    Also, you are making a comparison as part of the while conditional, which means you are only counting a successful comparison, which is why your best case result is wrong. `compcount++` should also be right above the while loop. – Mranz Nov 08 '11 at 14:35
  • I dont know why you find it wrong when I m getting the right results with this code.This is not only straying away from my main question but I didnt ask whether my code is right or not.I've tested this code already and posted it on here. – Mahi Vattekat Nov 08 '11 at 14:35
  • @MahiVattekat From your code, j is always greater than 0 because you assign it to 1 and only increment it. The only time it will ever be less than 0 is if you overflow it. – Mranz Nov 08 '11 at 14:36
  • Then can you explain why I get the results of the sorted list? – Mahi Vattekat Nov 08 '11 at 14:38
  • @Mahi: We are talking about this because a) there is no point in counting comparisons in a faulty algorithm and b) your code is basically impossible to comprehend. – Björn Pollex Nov 08 '11 at 14:38
  • @Mranz J has to be always greater than 0.But array[t] doesnt have to always be greater than key .Which is the number after array[t] – Mahi Vattekat Nov 08 '11 at 14:38
  • I've searched alot online for the insertion sort algorithm method AND this is the algorithm that we were taught as well. – Mahi Vattekat Nov 08 '11 at 14:39
  • @MahiVattekat The j > 0 check is either not useful, as used in your code, or an indication of a bug in your code elsewhere. – Mranz Nov 08 '11 at 14:41
  • I dont know why you find it strange for j to be greater than 0. That isn't as important as array[t]>key condition.array[j] is the second element initially so j can never be 0. – Mahi Vattekat Nov 08 '11 at 14:41
  • @MahiVattekat **array[j] is the second element initially so j can never be 0** is exactly why I find it strange. Why are you checking it? – Mranz Nov 08 '11 at 14:45
  • Because it's supposed to check whether the list is sorted right? so if there's a second element it should always check whether the element before it is greater or not – Mahi Vattekat Nov 08 '11 at 14:48
  • @MahiVattekat See jpalecek's answer to see why the `j > 0` check was a red flag. – Mranz Nov 08 '11 at 14:53
  • Im sorry I believe I found out why it was wrong.The algorithm I wrote in the book had j so I put it on code .EVEN though it worked ,it makes more sense now when it is t>=0 – Mahi Vattekat Nov 08 '11 at 14:54

2 Answers2

2

You are making a comparison as part of the while conditional, which means you are only counting a successful comparison, which is why your best case result is wrong. compcount++ should also be right above the while loop.

Edit:

compCount++;
while (t >= 0 && array[t] > key)
{
    array[t+1] = array[t];//moving array if bigger than next element
    t = t-1;

    if (t >= 0) // This is a hack to ensure that 't >= 0' will pass
       compCount++; // and another comparison will happen
}
Mranz
  • 1,260
  • 1
  • 12
  • 20
  • When I use compcount++ inside the while loop for the worst case scenario it comes true according to the theoretical value. But when I do compcount ++ in the while loop for the best case scenario , it's 0. Should I be putting compcount++ out of the while loop while doing the best case input? – Mahi Vattekat Nov 08 '11 at 16:31
  • It needs to be in both places. Right outside the while loop to catch the first comparison, and inside the while loop to catch each subsequent comparison. It may seem like an odd process flow, because it is, but it works. – Mranz Nov 08 '11 at 16:33
  • If thats the case the worst case scenario comes with 527 times opposing 496 .496 is right when I put in the (n^2-n)/2 formula for 32.But it isnt 527 theoretically.So that cant be true for the worst case – Mahi Vattekat Nov 08 '11 at 16:35
  • oops no i was right .It is 527 again.So it cant be in both places – Mahi Vattekat Nov 08 '11 at 16:39
  • You are right. The problem is that your comparison is the second condition to the while loop. Each time your full while conditional executes, you need to increment compCount. You could wrap the `compCount++` in the while loop to be: `if (t >= 0) { compCount++; }`. This looks really bad and you might consider re-working the code, but it will ensure that compCount will only get incremented if the entire while conditional gets executed. – Mranz Nov 08 '11 at 16:40
  • put a seperate if(t>=0) {compcount++;) ? – Mahi Vattekat Nov 08 '11 at 16:43
  • is the number of key comparisons for random data input always random ???Thats what I keep getting – Mahi Vattekat Nov 08 '11 at 17:03
2

There's one error in your program

           while (j > 0 && array[t]>key)

should be

           while (t >= 0 && array[t]>key)

Other than that, it works for me with the inverse sorted input. It is indeed the worst case and the result clearly shows it.

You've got the result off by n-1, but that's a minor problem. For a solution, see @Mranz's answer.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • The worst case input should have (n^2-n)/2 times comparisons right? – Mahi Vattekat Nov 08 '11 at 14:53
  • 1
    @MahiVattekat: We don't want `t` to underflow the array. `j>0` doesn't make sense, since `j` is unchanged during the loop. – jpalecek Nov 08 '11 at 14:53
  • Because t actually decrements and therefore you run the risk of decrementing it below 0. – Mranz Nov 08 '11 at 14:53
  • Yes sorry I just realised that checking for j is unneccessary when we are indeed decrementing t – Mahi Vattekat Nov 08 '11 at 14:56
  • Thank you very much!!!It indeed IS (n^2-n)/2 times for the worst case input!!thank you thank you – Mahi Vattekat Nov 08 '11 at 15:00
  • just one question ,in that code of yours , how did you generate the numbers 1 - 32? And the sort looks just like mine how does it sort it reverse??? – Mahi Vattekat Nov 08 '11 at 15:06
  • @MahiVattekat: The sort code IS yours (with t/j the error fixed), and it doesn't sort reversed (although it would be a matter of just changing `<` to `>`). I generate numbers -1..-32 (note they're negative) with `std::generate` and lambda from c++11. The number come out properly sorted from the lowest (that's -32) up. – jpalecek Nov 08 '11 at 15:12
  • You still sorted from (n - 0) that is the worst case input.I havent seen this generate method or this lambda method before in C++. What exactly is it doing in that line? – Mahi Vattekat Nov 08 '11 at 15:15
  • @MahiVattekat: lambdas: http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11. std::generate with example: http://msdn.microsoft.com/en-us/library/46h7chx6.aspx. In that line, the lambda is a function that gets called for each element of the array, decrementing `n` and returning the decremented value. std::generate takes this value and puts it into the array. – jpalecek Nov 08 '11 at 15:31
  • Thanks but I found another method of decrementing the value of n without the negative sign by assigning the value of the size of the array to an integer variable initially and using it in the for loop . Its amazing!Just that one letter from j to t changed EVERY thing! – Mahi Vattekat Nov 08 '11 at 15:54