我有一个选择排序的代码,我写了一年前在Python这里,但是当我试图把它适应C ++,它只是完全停止工作,且算法,这在逻辑上是完全一样的,不同的排序算法,并打印出一团糟。
void SelectionAscending2(int array[], int numItems)
{
int count;
int temp;
int minimum;
int Pass = 0;
//while (Pass < numItems)
for (int i = Pass; i < numItems; i++)
{
count = Pass + 1;
minimum = Pass;
//while (count <= numItems)
for (int j = count; j <= numItems; j++)
{
if (array[count] < array[minimum])
{
minimum = count;
count += 1;
}
}
temp = array[Pass];
array[Pass] = array[minimum];
array[minimum] = temp;
Pass += 1;
}
for (int i = 1; i < numItems; i++)
{
cout << array[i] << ", ";
}
}
int main()
{
int myArray[8] = { 4, 2, 1, 3, 6, 5, 8, 7 };
int length = sizeof(myArray) / sizeof(myArray[0]);
SelectionAscending2(myArray, length);
}
这段代码在python中工作得很好,但是在C ++中却输出了它:2, 3, 4, 5, 6, 0, 7,
我已经为此苦苦挣扎了3天,但我所做的一切都没有起作用。
实际上,您已经从python代码中转移了一些。
在python代码中,您已将设置为length of array (numItems)
,actual length - 1
但在此处与放置了length (numItems)
相同的内容actual length
。
另外,在打印时,您从i = 1开始打印。这就是为什么您的代码无法按预期工作的原因。
因此,您可以进行以下更改(方法之一):
j <= numItems
在第二个for循环中更改为j < numItems
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句