从两端用 Min 和 Max 进行选择排序
Selection Sort from both ends with Min and Max
我想知道为什么这段代码没有输出正确的数字序列(升序)。它取自此 material - Upgraded Selection Sort。例如,当我插入像这样的数组值时 - [8,5,6,1,4,7,3,0,2,9] 它 returns - [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]<<" ";
}
}
在 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);
}
论文中发表的 pseudo-code 中似乎有一个 错别字 。最后一部分:
else if(max!= n-1-i)
只需删除 else
.
这与作者对算法的描述的 5.i 和 5.ii 部分相对应(更好)。
我想知道为什么这段代码没有输出正确的数字序列(升序)。它取自此 material - Upgraded Selection Sort。例如,当我插入像这样的数组值时 - [8,5,6,1,4,7,3,0,2,9] 它 returns - [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]<<" ";
}
}
在 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);
}
论文中发表的 pseudo-code 中似乎有一个 错别字 。最后一部分:
else
if(max!= n-1-i)
只需删除 else
.
这与作者对算法的描述的 5.i 和 5.ii 部分相对应(更好)。