C语言 如何使用指针执行冒泡排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16264823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Perform Bubble Sort using Pointers
提问by user1800923
I have written this code for Bubble Sort using Pointers, but I am getting errors like LVALUE required.
我已经使用指针为冒泡排序编写了这段代码,但我收到了像 LVALUE 需要这样的错误。
Here is my code. Please fix this code. I am getting error basically in swapping syntax. Please help
这是我的代码。请修复此代码。我基本上在交换语法中遇到错误。请帮忙
#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;
}
}
}
}
回答by Theodoros Chatzigiannakis
Better make your swapping section like this:
最好让你的交换部分像这样:
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
Especially if you're a beginner in C, fancy syntax with pointer math for simple array access doesn't help you understand your own code.
特别是如果您是 C 的初学者,用于简单数组访问的带有指针数学的花哨语法并不能帮助您理解自己的代码。
Also, you probably want to call your sorting function like this: sort(a, n), because aalready means &a[0]in C. If you start throwing more reference operators you'll end up accessing other memory than what you intend.
此外,您可能想像这样调用排序函数:sort(a, n),因为在 C 中a已经意味着&a[0]。如果您开始抛出更多引用运算符,您最终将访问其他内存,而不是您想要的。
回答by BlackBear
You are just missing a couple of parenthesis:
你只是缺少几个括号:
if(*(a+j)==*(a+j+1))
{
temp=*(a+j);
*(a+j)=*(a+j+1);
*(a+j+1)=temp;
}
They are needed because you want to add j to a, thento dereference that address.
需要它们是因为您想将 j 添加到 a,然后取消引用该地址。

