2013-11-28 36 views
-8

我需要兩個數組(第一個,上升;以及所述第二一個降序)排序兩個陣列排序在C + +

這裏不用在排序完成的代碼: -

for(int i=0;i<10;i++)      //1st array, ascending 
{ 
    for(int j=0;j<10;j++) 
    { 
     if(array1[j]>array1[j+1]) 
     { 
      int temp=array1[j]; 
      array1[j]=array1[j+1]; 
      array1[j+1]=temp; 
     } 
    } 
}           //Over 

for(int i=0;i<10;i++)      //2nd, descending 
{ 
    for(int j=0;j<10;j++) 
    { 
     if(array2[j]<array2[j+1]) 
     { 
      int temp=array2[j]; 
      array2[j]=array2[j+1]; 
      array2[j+1]=temp; 
     } 
    } 
}           //Over 

當我嘗試打印這些,它在某個地方搞砸了,我無法查明代碼中的問題。謝謝..

+4

'std :: sort'有什麼問題? – 111111

+0

數組的大小是多少? 10? 11? – deepmax

+3

「它擰在某處」 - 有史以來最好的描述。 – Shoe

回答

0

就不得不內環限制固定代碼:

for(int i=0;i<10;i++)      //1st array, ascending 
{ 
    for(int j=0;j<9;j++) 
    { 
     if(array1[j]>array1[j+1]) 
     { 
      int temp=array1[j]; 
      array1[j]=array1[j+1]; 
      array1[j+1]=temp; 
     } 
    } 
}           //Over 

for(int i=0;i<10;i++)      //2nd array, descending 
{ 
    for(int j=0;j<9;j++) 
    { 
     if(array2[j]<array2[j+1]) 
     { 
      int temp=array2[j]; 
      array2[j]=array2[j+1]; 
      array2[j+1]=temp; 
     } 
    } 
}          //Over 

謝謝你們!

1

您可以使用C++本身使用您想要的任何有效規則對數組進行排序(相當有效)。如果您希望按升序排列,則可以使用默認類型,它會自動有效地使用<。如果你想要降序,你只需要使用相反的比較,即>

實施例:

#include <vector> 
#include <algorithm> 
#include <functional> 
#include <iterator> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    vector<int> makeAscending = {3,2,1}; 
    vector<int> makeDescending = {4,5,6}; 

    sort(begin(makeAscending), end(makeAscending)); // could pass less<int>() if you wanted 
    sort(begin(makeDescending), end(makeDescending), greater<int>()); 

    // print to see answer 
    copy(begin(makeAscending), end(makeAscending), ostream_iterator<int>(cout, " ")); 
    cout << endl; 
    copy(begin(makeDescending), end(makeDescending), ostream_iterator<int>(cout, " ")); 
} 

只是要精確,用於分選的有效規則是一個產生在容器中的物品的弱排序。維基百科頁面有規則,但它們大多數是這樣的(呼叫任何一般的「規則」符號<和x,y,z是您的容器中的項目):

1.)x < x從來都不是真的。

2.)如果x < y爲真,則意味着y < x爲false。 (如果x < y爲假且y < x是假的,它們被看作是「相等」)

3.)如果x < y爲真和y < z爲真,則x < z是真實的。

+0

謝謝,但正如我已經評論過的,我必須手動解決這個特定的問題(for循環n所有),所以這不會幫助。 – Preformer