c - 冒泡排序需要很长时间然后出现段错误

标签 c bubble-sort

Given an integer n, write a C program to count the number of digits that are in the same position after forming an integer m with the digits in n but in ascending order of digits. For example, if the value of n is 351462987 then value of m will be 123456789 and digits 4 and 8 will be in the same position.

这是我的代码:

#include<stdio.h>

void bubble(int a[],int length)
{
    for (int i=0;i<length;i++)
    {
        for (int j=0;j<length;j++)
        {
            if (a[j]>a[j+1])
            {
                int t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
    }
}
int check(int a[],int b[],int length)
{
    int count=0;
    for (int i=0;i<length;i++)
    {
        if (a[i]==b[i])
        {
            count=i;
            break;
        }
    }
    return count;
}
int length(int n)
{
    int l;
    while (n!=0)
    {
        n=n/10;
        l++;
    }
    return l;
}
void main()
{
    int n,arrn[100],temp[100];
    scanf("%d",&n);
    int l=length(n);
    for (int i=0;i<l;i++)
    {
        arrn[l-i-1]=n%10;
        temp[l-i-1]=arrn[l-i-1];
        n=n/10;
    }
    bubble(temp,l);
    int c=check(arrn,temp,l);
    printf("%d",c);
}

我能够编译代码,但是当我执行它时,需要很长时间才能显示段错误。

最佳答案

简单回答,使用调试器

您的代码存在一些问题:

  • length函数,l未初始化,因此可以具有任意初始值。就您而言,您可能希望从 0 开始。

    int l = 0;
    
  • 您的check函数可能无法执行您想要的操作。如所写count不是计数,而是数字匹配位置的索引。因为有一个break语句 block 中,循环将在第一个匹配项后退出,因此返回值将是第一个匹配项的位置,如果没有找到匹配项,则返回值为 0。

  • 您的bubblei 时,函数会超出一项等于length - 1当您访问项目 a[j + 1] 时在超出范围的内循环中。在这种情况下,从 1 而不是从 0 开始并比较索引 i - 1 处的项目会更简单。索引为 i 的项目.

一些额外的说明:

  • 建议在运算符周围以及分隔多个声明的逗号后添加空格,以提高可读性。以下是一些可读性更高的行示例。

    int n, arrn[100], temp[100];
    int count = 0;
    for (int i = 0; i < length; i++)…
    if (a[i] == b[i])…
    arrn[l - i - 1] =n % 10;
    temp[l - i - 1] = arrn[l - i - 1];
    int check(int a[], int b[], int length)
    
  • 您应该编写一个函数并确保其正常工作,而不是一次编写多个函数。顺便说一句,将数字拆分为数字的循环也可以是一个函数。

    • 尝试使用较小数字(例如 12 或 21)的函数
    • 为变量使用更好的名称。 arrntemp不是很清楚。 originalsorted可能会更好。

关于c - 冒泡排序需要很长时间然后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042793/

相关文章:

Java - 如何在冒泡排序后将值打印为单词?

c - BSS 是程序文件的一部分吗?

c - 如何在 C 中使用 sscanf 扫描多个单词?

c - C 中文件的冒泡排序

c++ - 对 vector 中的正 NaN 和负 NaN 进行排序

jQuery swapsies 不适用于多个 Action

c - C 中 void 函数的返回值不清楚

c - 任意指针之间的距离

java - 父子权限被拒绝

java - Java 二维数组上的冒泡排序