加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 选择从最小和最大两端排序

发布时间:2020-12-16 06:53:05 所属栏目:百科 来源:网络整理
导读:我想知道为什么这段代码没有输出正确的数字序列(升序).它取自这个材料– Upgraded Selection Sort.例如,当我插入像这样的数组值 – [8,5,6,1,4,7,3,2,9]它返回 – [0,8,9. #includeiostreamusing namespace std;void Swap(int Arr[100],int Temp_min,int Tem
我想知道为什么这段代码没有输出正确的数字序列(升序).它取自这个材料– Upgraded Selection Sort.例如,当我插入像这样的数组值 – [8,5,6,1,4,7,3,2,9]它返回 – [0,8,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,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,max);
                Swap(Arr,min);
            }
            else
            {
                if(min != i)
                {
                    Swap(Arr,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]<<" ";
    }
}

解决方法

在本文中发表的伪代码中似乎存在拼写错误.在最后一部分:

else if(max!= n-1-i)

只需删除其他人.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读