C中的自定义冒泡排序

标签 c sorting

我想了解我的代码有什么问题,我是 C 语言的初学者,但是我用 Java 进行了大量编程。我使用 8 个整数为冒泡排序制作了自己的“惰性”实现,但它会导致无限循环。

一些解释:尝试将 8 个整数从大到小排序,并使用计数器确定何时对所有值进行排序

#include <stdio.h>
int main()
{
int array[8];
int counter =0;
int storage=0;
int i;
printf("Please enter 8 numbers:");
scanf("%d%d%d%d%d%d%d%d",&array[0],&array[1],&array[2],&array[3],&array[4],&array[5],&array[6],&array[7]);
while (counter!=7)
{
    counter =0;
for (i=0; i<=6;i++)
{
    if (array[i]<=array[i++])
    {
        storage = array[i];
        array[i]= array[i++];
        array[i++]= storage;
    }
    else
    {
        counter++;
    }
}
}
printf("%d%d%d%d%d%d%d%d",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);

最佳答案

您需要更改以下代码:

if (array[i]<=array[i++])
{
    storage = array[i];
    array[i]= array[i++];
    array[i++]= storage;
}

if (array[i]<array[i+1])//++ is post increment operator and you are changing index value with every comparison and assignment
{
    storage = array[i];
    array[i]= array[i+1];
    array[i+1]= storage;
}

无限循环的另一个原因是当你交换两个元素时你不会增加计数器的值。因此,无论是否交换两个元素,都应该将其从 else 部分中删除并使其在 for 循环中通用。或者你可以 while (counter != 0) {counter = 0; ...} 所以它修改了冒泡排序。

关于C中的自定义冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128255/

相关文章:

c - strtok() 然后 strcmp() 当 true 时返回 false

c++ - 如何在Windows上正确打印处理线程?

java - 根据 int 数组的第一个和第二个元素对 int 数组的数组列表进行排序

python - 在 Jython/Python 中对二维列表进行排序

linux - 根据字符串中的特定值进行排序。

Python:从范围(n)生成k元组,仅按顺序包含元组

c - GtkSpinner 具有持久的功能与 C

c - C函数中静态volatile变量的返回值

C 自由函数(不使用 malloc)

mongodb - 为什么字段上的索引的大小取决于它在 MongoDB 中是升序还是降序