c - C程序中使用指针排序

标签 c sorting pointers

我使用 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/

相关文章:

c - 从 func() 到 __func() 的间接寻址

c - numa、mbind、段错误

c - 静态链接 C++ 库失败

c - 如何为 %20s 的 scanf 删除额外输入

android - 在android中用指针绘制图表

algorithm - QuickSort Dijkstra 三向分区 : why the extra swapping?

c# - 按计算值排序列表

c++ - 合并和快速排序 - 堆栈重载

c++ - 提取符号之间的字符串

c - 通过指针表示法写入二维数组