简体   繁体   English

C语言上的基本插入排序算法(TDM-GCC编译器)

[英]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: 手动代码可以正常工作,但是使用TDM-GCC编译器在Dev C ++上显示了错误的输出:

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. B的大小实际上是元素数乘以数据类型的大小,因此它太大了。 You should have this instead: 您应该改为:

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

Also, your for loop condition is incorrect. 另外,您的for循环条件不正确。 You have: 你有:

i >= n-1 

Which will always be false, so the loop will never be entered. 它将始终为假,因此将永远不会进入循环。 It should be: 它应该是:

i <= n-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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