【问题标题】:Selection Sort from both ends with Min and Max使用 Min 和 Max 从两端选择排序
【发布时间】:2017-05-30 18:00:55
【问题描述】:

我想知道为什么这段代码没有输出正确的数字序列(升序)。它取自此材料 - Upgraded Selection Sort。例如,当我插入这样的数组值时 - [8,5,6,1,4,7,3,0,2,9] 它返回 - [0,1,3,4,5,7,8, 6,2,9]。

#include<iostream>
using namespace std;

void Swap(int Arr[100],int Temp_min,int Temp_max)
{
    int temp;
    temp = Arr[Temp_min];
    Arr[Temp_min] = Arr[Temp_max];
    Arr[Temp_max] =temp;
}

void OptimizedSelectSort(int Arr[],int n)
{
    int i,j,min,max;

    for(i=0;i<n/2;i++)
    {
        min = i;
        max = i;
        for(j=i+1;j<n-i;j++)
        {
            if (Arr[j]> Arr[max])
            {
                max = j;
            }
            else if (Arr[j]< Arr[min])
            {
                min = j;
            }
        }
        if (i == max && n-1-i == min)
        {
            Swap(Arr,min,max);
        }
        else
        {
            if ((min == n-1-i) && (max != i))
            {
                Swap(Arr,i,min);
                Swap(Arr,n-1-i,max);
            }
            else if ((max == i) && (min != n-1-i))
            {
                Swap(Arr,n-1-i,max);
                Swap(Arr,i,min);
            }
            else
            {
                if(min != i)
                {
                    Swap(Arr,i,min);
                }
                else if(max!= n-1-i)
                {
                    Swap(Arr,max,n-1-i);
                }
            }
        }
    }
}

int main()
{
    int n;
    cout<<"Enter the size of array"<<endl;
    cin>>n;
    int * Mas;
    Mas = new int [n];
    int i;
    cout<<"Enter the elements"<<endl;
    for(i=0;i<n;i++)
    {
        cin>>Mas[i];
    }
    OptimizedSelectSort(Mas, n);
    cout<<"Sakartots saraksts:";

    for(i=0;i<n;i++)
    {
        cout<<Mas[i]<<" ";
    }
}

【问题讨论】:

    标签: c++ selection-sort


    【解决方案1】:

    论文中发布的伪代码中似乎有一个错字。在最后一部分:

    否则if(max!= n-1-i)

    只需删除else

    这对应于(更好地)作者对算法的描述的第 5.i 和 5.ii 部分。

    【讨论】:

      【解决方案2】:

      在 for 循环 i 中,我会输入:

        min = i;
        max = n-i-1;
      

      并在 OptimizedSelectSort 结束时:

      if (min != i)
      {
          Swap(Arr, i, min);
      }
      //no else here
      if (max != n - 1 - i)
      {
          Swap(Arr, max, n - 1 - i);
      }
      

      【讨论】:

      • 不,也不是那样工作的。有趣的是,初始代码在数组大小为 8 时中断,数组大小为 8 的所有内容都正确排序。
      • 您对“其他删除”的看法是对的。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      相关资源
      最近更新 更多