选择排序输出不正确

selection sort output is not correct

本文关键字:不正确 输出 排序 选择      更新时间:2023-10-16

我正在尝试用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; 
}       
   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;   

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