2015-12-08 29 views
0

所以我的程序有一個函數,我從文本文件中讀取數字到數組中,然後按升序對它們進行排序。但是,不要按升序排序,我的代碼按降序排序。爲了讓我的代碼按照我需要的方式工作,需要在這裏更改哪些內容?切換數組排序從降序升序

void displaySortedNums(string fileName) 
{ 
    ifstream inFile; 
    inFile.open(fileName + ".txt"); 
    int numbers[50]; 
    int arraySize = 0; 

    if (!inFile.is_open()) 
     { 
      cerr << "\nUnable to open file " << endl << endl; 
     } 
    if (inFile.peek() == std::ifstream::traits_type::eof()) 
     { 
      cout << "\nData file is empty" << endl << endl; 
      cout << "File Successfully Read" << endl << endl; 
     } 
    else 
     { 
      inFile >> numbers[arraySize]; 
      while (inFile) 
       { 
        arraySize++; 
        inFile >> numbers[arraySize]; 
       } 
      numbers[arraySize] = '\0'; 
      double temp; 
      for (int i = 0; i < arraySize + 1; i++) 
      for (int j = 0; j < arraySize + (i + 1); j++) 
        if (numbers[j] < numbers[j + 1]) 
        { 
         temp = numbers[j]; 
         numbers[j] = numbers[j + 1]; 
         numbers[j + 1] = temp; 
        } 
      for (int i = 0; i < arraySize; i++) 
      { 
       cout << numbers[i] << endl; 

      } 
     } 

    system("PAUSE"); 
    return; 
} 
+2

找出你在比較元素的位置並切換操作符?另外你爲什麼不使用'std :: sort'? – Kevin

+0

也許應該if(numbers [j] numbers [j + 1])''? – skypjack

+0

使用'std :: sort'? –

回答

1

你應該改變這一行:

if (numbers[j] < numbers[j + 1]) 

使用下面的一個,而不是:

if (numbers[j] > numbers[j + 1]) 

的基本思想是很簡單實在,你正在檢查,如果第二種情況數字大於其後繼者,而在第一個中你正在檢查相反的東西。