为什么我的自适应选择排序算法在C++; 我在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); } void selection搜索2(int数组[],int numItems) { 整数计数; 内部温度; 最小整数; int Pass=0; //while(通过

为什么我的自适应选择排序算法在C++; 我在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); } void selection搜索2(int数组[],int numItems) { 整数计数; 内部温度; 最小整数; int Pass=0; //while(通过,c++,sorting,selection-sort,C++,Sorting,Selection Sort,实际上您已经从python代码中转移了一点 在python代码中,您已经设置了数组长度(numItems) 到实际长度-1,但这里您将长度(numItems)与实际长度相同 而且在打印的时候,你是从i=1开始打印的,这就是为什么 您的代码未按预期工作 因此,您可以进行以下更改(方法之一): Changej您创建的for循环并不是python代码中while循环的完全替代品。我尝试使用while循环,但即使在等待几分钟后也没有打印到控制台,因此我被迫使用for循环loops@Michael

实际上您已经从python代码中转移了一点

  • 在python代码中,您已经设置了数组长度(numItems) 到
    实际长度-1
    ,但这里您将
    长度(numItems)
    实际长度
    相同

  • 而且在打印的时候,你是从i=1开始打印的,这就是为什么 您的代码未按预期工作

因此,您可以进行以下更改(方法之一):


  • Change
    j您创建的for循环并不是python代码中while循环的完全替代品。我尝试使用while循环,但即使在等待几分钟后也没有打印到控制台,因此我被迫使用for循环loops@MichaelChourdakis是的,我试过稍微修改一下,但仍然不起作用。除非语法是正确的错了,我不知道发生了什么事