gpt4 book ai didi

c - 如何使用指针执行冒泡排序

转载 作者:行者123 更新时间:2023-11-30 21:13:47 25 4
gpt4 key购买 nike

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

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

#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;
}
}
}
}

最佳答案

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

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

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

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

关于c - 如何使用指针执行冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16264823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com