-3

我正在尝试在 C++ 中实现选择排序。我不知道我在这段代码中做错了什么,但结果排序不正确。请让我知道我做错了什么。谢谢您的帮助。

输出结果: 23 31 4 89 2 8 10 11

#include <iostream>

using namespace std;

void printElement(int arr[],int size)
{
  for(int i = 0; i < size; i++)
      cout << arr[i] << "  ";            
}


// arr[] = {31, 23, 4, 89, 2, 8, 10, 11}
void selectionSort(int arr[], int size)
{     
   int i, j, min, min_id,  tmp;

   for(i = 0; i < size-1; i++){
       min = arr[i];
       for(int j = i + 1; j < size; j++){
           if (arr[j] < min){
                min = arr[j];
                min_id = j;   
           } 
           tmp = arr[i]; //tmp = min; - this is wrong by msl
           arr[i] = arr[min_id]; //min = arr[min_id]; this is wrong by msl
           arr[min_id] = tmp;   
       }   
       printElement(arr, size); 
       cout << endl;  
   }  
}


int main()
{
    int size = 8;
    int arr[] = {31, 23, 4, 89, 2, 8, 10, 11};
    selectionSort(arr, size);
    printElement(arr, size);

    system("PAUSE");
    return 0; 
}       
4

1 回答 1

1
   tmp = arr[i]; //tmp = min; - this is wrong by msl
   arr[i] = arr[min_id]; //min = arr[min_id]; this is wrong by msl
   arr[min_id] = tmp;   

以上内容位于循环的错误部分。在选择排序中,交换发生在外循环——而不是内循环。

于 2013-08-26T00:38:44.653 回答