【发布时间】:2021-11-26 17:17:52
【问题描述】:
我使用动态数组和指针制作了一个选择排序程序,但是在运行此代码后,我发现如果我们给出像 4 和 6 这样的大小输入,则数组正在排序,但如果大小输入像 5,则不能正确排序和7等......在此之前我也使用相同的指针和动态数组技术进行了冒泡排序程序,但它在所有条件下都给出了完美的排序数组,我也尝试调试代码但仍然不明白为什么会这样如果有人对此有所了解,请帮助我。
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int * ptr,temp,min;
int size,i,j,s;
printf("Enter the size of array:");
scanf("%d",&size);
ptr = (int *)(calloc (size,sizeof(int)));
if(ptr == NULL)
printf("No memory");
else
{
printf("\n=== RANDOM ELEMENTS OF ARRAY ===\n");
for(s=0;s<size;s++)
*(ptr+s) = rand()%100;
for(s=0;s<size;s++)
printf("\nElement [%d] = %d ",s,*(ptr+s));
// selection sort algorithm
for(i=0;i< size-1;i++)
{
min = i;
for(j=i+1;j<size;j++)
{
if(*(ptr+j) < *(ptr+min))
{
min = j;
}
temp = *(ptr+i);
*(ptr+i) = *(ptr+min);
*(ptr+min) = temp;
}
}
// End of algorithm
printf("\n\n======= SORTED ELEMENTS =======\n\n");
for(s=0;s<size;s++)
printf("Element [%d] = %d \n",s,*(ptr+s));
}
}
【问题讨论】:
-
不是核心问题,但在
C这个演员表是错误的:ptr = (int *)(calloc (size,sizeof(int)));使用ptr = calloc (size,sizeof(int)); -
@ryyker。据我所知,这是不必要的,不一定是完全错误的
-
如果原始数组是
3, 2, 1,循环的第一次迭代交换2和3给你2,3,1。下一次迭代交换1和3,但1永远不会替换2。你的算法不正确。
标签: arrays c sorting pointers dynamic-arrays