我使用動態陣列和指標制作了一個選擇排序程式,但在運行此代碼后,我發現如果我們提供 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));
}
}
uj5u.com熱心網友回復:
你的Selection Sort演算法似乎是錯誤的。在內部 for 回圈完成迭代后,您必須用最小值替換當前索引中的元素:
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;
}
現在,它應該適用于所有輸入尺寸。
uj5u.com熱心網友回復:
清除一些不必要的混淆因素......
*(ptr index)
與
ptr[index]
但第二個更容易閱讀。
接下來,在下一節中,變數min被引入,
if(*(ptr j) < *(ptr min))
{
min = j;
}
...但不是簡單排序所必需的。只要堅持使用i和j,對于偶數或奇陣列的值,排序都會正確進行。最后,為了消除記憶體泄漏,不再需要free(ptr);時呼叫ptr。以下是經過修正的清理版本。
int main(void)//added void
{
int * ptr,temp/*,min*/;
int size,i,j,s;
printf("Enter the size of array:");
scanf("%d",&size);
ptr = calloc (size,sizeof(int));//casting is required in C
//but unnecessary in C.
//(and can be problematic)
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 )
{
for(j=i 1;j<size;j )//removed if section introducing 'min'
{
if(ptr[j] < ptr[i])
{
temp = ptr[i];
ptr[i] = ptr[j];
ptr[j] = 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));
free(ptr);
}
return 0;//added
}
順便說一句,這是用 size == 3 和
ptr[0] = 3;
ptr[1] = 2;
ptr[2] = 1;
以及其他幾個隨機值的奇數和偶數計數
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315005.html
下一篇:C中指標的寬度(以位元組為單位)
