简体   繁体   中英

Why does my algorthim for insertion sort return different values , when I use the same value in condition statement?

# At first case I put the temp variable to condition statement in while loop#

  int tab[8]={0,1,7,8,7,6,5,2};
    int n=8;                
    int j;
    int temp;


    for(int i=1;i<n;i++)
    {
        temp=tab[i];
        j=i-1;

        while(j>=0&&tab[j]>temp)
        {
            tab[j+1]=tab[j];
            --j;    
        }
        tab[j+1] = temp;

    }

And the resault that I get is :

0 1 7 8 7 6 5 2
0 1 2 5 6 7 7 8

But on the other hand when instead I use tab[i] in condition statement in while loop

for(int i=1;i<n;i++)
{
    temp=tab[i];
    j=i-1;

    while(j>=0&&tab[j]>tab[i])
    {
        tab[j+1]=tab[j];
        --j;    
    }
    tab[j+1] = temp;

}

I get this result:

0 1 7 8 7 6 5 2
0 1 7 7 6 5 2 8

And I can't find any difference between passing these values and why it behaves like that. I think that I am using the same values. It's mine first question on that page , be kind to me please, have a nice day

Because in first iteration of while loop if tab[j] > tab[i]

tab[j+1]=tab[j]; changes tab[i] to tab[i - 1] ,

So essentially your whole program in second case is equivalent to this

#include <iostream>

int main ()
{
    int tab[8]={0,1,7,8,7,6,5,2};
    int n=8;                
    int j;
    int temp;


    for(int i=1;i<n;i++)
    {
        temp=tab[i];
        j=i-1;

        if (tab[j]>tab[i])
        {
            tab[j+1]=tab[j];
            --j;    
        }
        tab[j+1] = temp;

    }

    for(auto&& a: tab) {
        std::cout << a << " ";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM