【问题标题】:How to Perform Bubble Sort using Pointers [closed]如何使用指针执行冒泡排序[关闭]
【发布时间】:2013-04-22 07:16:45
【问题描述】:

我已经使用指针为冒泡排序编写了这段代码,但我遇到了需要 LVALUE 之类的错误。

这是我的代码。请修复此代码。我基本上在交换语法时遇到错误。请帮忙

#include<stdio.h>
#include<conio.h>
void sort(int *a,int n);
void main()
{
    int a[20];
    int n,i;
    clrscr();
    printf("Program for BUBBLE SORT\n");
    printf("Enter the Number of ELements you want in Array\n");
    scanf("%d",&n);
    printf("Enter the Elements in UNSOTED ARRAY\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("The Unsorted ARRAY is:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\t",a[i]);
    }
    printf("\n");
    sort(&a,n);
    getch();
}
void sort(int *a,int n)
{
    int i,temp,j;
    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            if((*a+j)==(*a+j+1))
            {
                temp=*a+j;
                *a+j=*a+j+1;
                *a+j+1=temp;
            }
        }
    }
}

【问题讨论】:

  • 请正确格式化您的代码 - 目前的形式几乎无法阅读。
  • ..."请修复此代码"??
  • 请修复此代码。 不,您修复它。如果您不明白“LVALUE required”是什么意思,请询问(但请先搜索,因为我确信这里已经有很多答案了)。我们随时为您提供帮助,但这不是编码服务。

标签: c sorting bubble-sort


【解决方案1】:

最好让你的交换部分像这样:

temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;

特别是如果您是 C 初学者,用于简单数组访问的带有指针数学的花哨语法并不能帮助您理解自己的代码。

此外,您可能希望像这样调用排序函数:sort(a, n),因为在 C 中a 已经意味着&amp;a[0]。如果您开始抛出更多的引用运算符,您最终将访问其他内存而不是您的内存打算。

【讨论】:

    【解决方案2】:

    你只是少了几个括号:

    if(*(a+j)==*(a+j+1))
    {
        temp=*(a+j);
        *(a+j)=*(a+j+1);
        *(a+j+1)=temp;
    }
    

    它们是必需的,因为您想将 j 添加到 a,然后 以取消引用该地址。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多