简体   繁体   中英

Basic Insertion Sort Algorithm on C (TDM-GCC compiler)

Was learning basic sorting techniques, got stuck on Basic Insertion Sorting Algorithm I implemented myself. The code is working fine by hand, but showing incorrect output on Dev C++ using TDM-GCC compiler:

int B[6] = {7, 44, 6, 12, 90, 111234};
int n = sizeof(B);
int i = 0;
int val = 0;
int hole = 0;

for (i = 1; i >= n-1; i++)
{
    val = B[i];
    hole = i;

    while(hole>0 && B[hole-1]>val)
    {
        B[hole] = B[hole-1];
        hole = hole - 1;
    }
    B[hole] = val;
}

printf("The Sorted Values are:\n");

for(i=0;i<n;i++)
    printf("%d ", B[i]);

return 0;

Can anyone help please?

There are two issues:

int n = sizeof(B);

The size of B is actually the number of elements times the size of the datatype, so it's too big. You should have this instead:

int n = sizeof(B) / sizeof(B[0]);

Also, your for loop condition is incorrect. You have:

i >= n-1 

Which will always be false, so the loop will never be entered. It should be:

i <= n-1

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