【问题标题】:Applying selection sort on an array of integers对整数数组应用选择排序
【发布时间】:2020-12-11 07:19:06
【问题描述】:
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i<size-1; i++){
    
    int temp = arr[i];
    
    for(int j = i+1; j < size; j++){
        
        if(arr[j] < temp){
            temp = arr[j];
        }
        
    }
    
    swap(temp, arr[i]);
}

我正在尝试对给定数组应用选择排序算法,但我得到的输出只有[1,1,1,1,1,1],我正在通过内部循环找到最小元素,我不知道出了什么问题?

【问题讨论】:

  • 想想swap(temp, array[i]); 做了什么。它本质上是array[i] = temp;,因为之后temp 就超出了范围
  • 恕我直言,在定义内容时不要说明数组的容量。让编译器弄清楚。这样,您就不会过度分配空间。示例:const int arr[] = {7,4,10,8,3,1};
  • array 定义在哪里?
  • @ThomasMatthews 然后做const auto size = sizeof(arr) / sizeof(*arr); 这样我们就可以在循环条件下使用它了吗?有什么意义?
  • 现在是 2020 年。我们都同意使用std::size吗?

标签: c++ sorting selection-sort array-algorithms


【解决方案1】:

稍微修改了你的代码;

您需要将reference(address) 传递给两个元素以代替交换内容

int arr[] = { 7, 1, 10, 8, 3, 11, 0, 12, 5, 8 };
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i < size; i++)
{
   auto temp = std::min_element( arr + i, arr + size );

   std::swap( arr[i], *temp );      
}

您必须添加algorithm 标头才能使用std::min_element

【讨论】:

    【解决方案2】:
    int arr[] = {7,4,10,8,3,1};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    for(int i = 0; i<size-1; i++){
        
        int temp = arr[i];
        int pos = i;
        
        for(int j = i+1; j < size; j++){
            
            if(arr[j] < temp){
                temp = arr[j];
                pos = j;
            }
            
        }
        
        if(pos != i)
            std::swap(arr[pos], arr[i]);
    }
    

    这应该可行。

    【讨论】:

      【解决方案3】:

      建议不要使用using namespace std;。您不应该的原因有很多;这个我就不说了。

      顺便说一句,我试图让你的一些变量保持不变,但老实说,我没有。最好创建解释代码在做什么的变量名。它使您的代码更加清晰易读。

      所以选择退出一个字母的变量。在for 循环中很好,但这是一种特殊情况。

      现在,@user4581301 和@Swift -Friday Pie 提出了另一种选择。此方法使用std::size 使用c++17

      例如:

      #include <iostream>
      #include <utility> // to use the swap() function.
      #include <iterator> // to use std::size() function.
      
      
      int main()
      {
          int arr[] = { 7,4,10,8,3,1 };
          // This --> int size = sizeof(arr) / sizeof(arr[0]); is archaic.
      
          const int length = static_cast<int>(std::size(arr)); // Call this something other than "size"; you can run into issues. 
         // We use static_cast<int>  as a implicit conversion, and the obvious std::size(arr)).
         
          
      
         // Going through the elements
      
          for (int StartOfIndex = 0; StartOfIndex < length - 1; ++StartOfIndex)
          {
              // smallest is the index of the smallest element we’ve encountered this iteration
      
              int smallest = StartOfIndex;
      
              // Looking for a smaller element..
              for (int current = StartOfIndex + 1; current < length; ++current)
              {
                  // if we found an element smaller than our last; take note.
                  if (arr[current] < arr[smallest])
      
                      smallest = current;
              }
      
              // swap StartOfIndex with smallest.
              std::swap(arr[StartOfIndex], arr[smallest]);
          }
      
          //Prints array.
          for (int index = 0; index < length; ++index)
              std::cout << arr[index] << " ";
      
          std::cout << "\n";
      
          return 0;
      }
      

      输出:1 3 4 7 8 10

      【讨论】:

        【解决方案4】:

        你在编写 for 循环条件时犯的第一个错误,不要使用swap(temp, array[i]);,但先尝试了解基础知识。

        #include <iostream>
        
        using namespace std;
        
        int findsmall(int arr[], int i, int size){
            int s, pos, j;
            s = arr[i];
            pos = i;
            for(j = i+1; j < size; j++){
                if(arr[j] < s){
                    s = arr[j];
                    pos = j;
                }
            }
            return pos;
        }
        
        int main() {
            
            int arr[] = {7,4,10,8,3,1};
            int size = sizeof(arr) / sizeof(arr[0]);
            int smallnum;
            int temp;
            int count = 0;
            
            cout << "Original array: ";
            
            for(int i = 0; i < size; i++){
                if(i < size - 1){
                cout << arr[i] << ", ";}
                else{
                    cout << arr[i];
                }
            }
            
            cout << endl;
            
            for(int i = 0; i < size; i++){
                smallnum = findsmall(arr,i, size);
                temp = arr[i];
                arr[i] = arr[smallnum];
                arr[smallnum] = temp;
                count++;
            }
            
            
            
            cout << "Sorted array: ";
            
            for(int i = 0; i < size; i++){
                if(i < size - 1){
                cout << arr[i] << ", ";}
                else{
                    cout << arr[i];
                }
            }
            
            cout << endl;
            
            return 0;
        }
        

        【讨论】:

          【解决方案5】:
          void swap(int *xp, int *yp)  
          {  
              int temp = *xp;  
              *xp = *yp;  
              *yp = temp;  
          }  
            
          void selectionSort(int arr[], int n)  
          {  
              int i, j, min_idx;  
            
              // One by one move boundary of unsorted subarray  
              for (i = 0; i < n-1; i++)  
              {  
                  // Find the minimum element in unsorted array  
                  min_idx = i;  
                  for (j = i+1; j < n; j++)  
                  if (arr[j] < arr[min_idx])  
                      min_idx = j;  
            
                  // Swap the found minimum element with the first element  
                  swap(&arr[min_idx], &arr[i]);  
              }  
          }  
          
          
          selectionSort(arr,size);
          

          这应该可行。

          【讨论】:

          • 避免滚动你自己的sortstd::sort 已经涵盖了几乎所有内置内容,如果必须,最好通过引用传递。
          猜你喜欢
          • 2023-03-15
          • 2021-11-02
          • 2022-01-03
          • 2016-08-15
          • 2023-03-10
          • 1970-01-01
          • 2013-08-30
          相关资源
          最近更新 更多