【发布时间】:2017-01-03 07:31:26
【问题描述】:
我之前为冒泡排序算法测试了名为“交换”的相同变量,它运行良好。现在,通过选择排序,变量即使在递增之后也会失去它的值。 任何帮助将不胜感激。
int list[] = {10, 5, 6, 3, 4, 11, 9, 7, 2};
int min = list[0], pos = 0, temp_max = 0;
// Loop until no swap is needed
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
int swaps = 0,
// Iterate through array to find min value
for (int i = j, y = sizeof(list) / sizeof(int); i < y; i++)
{
if (list[i] < min)
{
min = list[i];
pos = i;
}
}
// Insert min value in left most position and add 1 to swaps, meaning array is not yet sorted
if (pos > j)
{
temp_max = list[j];
list[j] = min;
list[pos] = temp_max;
swaps++;
}
// The error might occur here: "swaps" keeping value 0 after previous if statement ends
printf ("swaps = %d\n", swaps);
// If no swaps ocurred, array is sorted
if (swaps == 0)
{
// Print sorted array and return
}
}
【问题讨论】:
-
您可以在两个循环中使用
n,因为y始终与n具有相同的值。不过,这不会影响您的问题。 -
1)
int swaps = 0,无法编译。也许您想要int swaps = 0;即;而不是,2) 解决第一个问题后,我看不到swaps有任何问题 - 请参阅ideone.com/Z40FXl - 它增加得很好。确定您发布了正确的代码?
标签: c variables scope selection-sort