2017-01-15 97 views
3

我想知道爲什麼這段代碼沒有輸出正確的數字序列(升序)。它已從此材料中取得 - 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]<<" "; 
    } 
} 

回答

0

似乎有一個錯字在僞代碼正如論文中所發表的那樣。在最後一部分:

其他if(max!= n-1-i)

只需卸下else

這與作者對算法描述的第5.i和5.ii部分相對應(更好)。

+1

謝謝,它是正確的解決方案! – Pmal12

0

在for循環中我,再去讀地說:

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); 
} 
+0

不,也不這樣工作。有趣的是,初始代碼在數組大小爲8時中斷,數組大小爲8的所有內容都被正確排序。 – Pmal12

+0

對「其他刪除」的看法是正確的。謝謝! – Pmal12

相關問題