gpt4 book ai didi

c - 局部变量丢失其值 : selection sort algorithm

转载 作者:行者123 更新时间:2023-11-30 15:01:23 24 4
gpt4 key购买 nike

我之前测试了冒泡排序算法中名为“交换”的相同变量,它运行得很好。现在,通过选择排序,变量即使在递增后也会失去其值。任何帮助将非常感激。

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
}
}

最佳答案

将声明 int swaps = 0 移至 for 循环之外。

<小时/>

换句话说,改变这个:

for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
int swaps = 0;
...
}

对此:

int swaps = 0;
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
...
}

关于c - 局部变量丢失其值 : selection sort algorithm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41438497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com