我使用 C 中的指针编写了一个升序排序程序。从逻辑上讲,该程序按升序排序,但输出是降序。这个程序出了什么问题。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,i,j,t,*ptr,sum=0;
printf("Enter number of elements to sort : ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{ printf("Error occurred memory not allocated \n"); exit(0); }
printf("Enter the elements of Array \n");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++)
{
if( *(ptr+i) > *(ptr+j))
{
t = *(ptr+i);
*(ptr+i) = *(ptr+j);
*(ptr+j) = t;
}
}
}
for(i=0;i<n;i++)
{
printf("\n%d\n",*(ptr+i));
}
free(ptr);
}
最佳答案
两件事
1) 对于升序,把if语句改成
if( *(ptr+i) < *(ptr+j) )
2) 你不需要每次都检查整个数组。可以从上一个最低值的位置开始。
for(i=0; i<(n-1); i++){
for(j=i+1; j<n; j++) {
...
}
}
关于c - C程序中使用指针排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24283105/