2015-01-06 68 views
-5
// Number Sorting Algorithm - Trey Taylor 2014 
#include <iostream> 
#include <cstdlib> 
#include <string> 

using namespace std; 
    int main() { 
     int numbersort [] = {200, 85, 63, 4} 
     cout << "The numbers scrambled are: "; 
     cout << numbersort[0] << ", "; 
     cout << numbersort[1] << ", "; 
     cout << numbersort[2] << ", "; 
     cout << numbersort[3] << ", " << endl; 
     firstlast: 
     if (numbersort[0] > numbersort[1]) { 
      int temp = 0; 
      temp = numbersort[0]; 
      numbersort[0] = numbersort[1]; 
      numbersort[1] = temp; 
     } 
      if (numbersort[1] > numbersort[2]) { 
       int temp = 0; 
       temp = numbersort[1]; 
       numbersort[1] = numbersort[2]; 
       numbersort[2] = temp; 
      } 
       if (numbersort[2] > numbersort[3]) { 
        int temp = 0; 
        temp = numbersort[2]; 
        numbersort[2] = numbersort [3]; 
        numbersort[3] = temp; 
       } 
         while (numbersort[0] > numbersort[1]) { 
         goto firstlast; 
       } 
     cout << "The numbers unscrambled are: "; 
     cout << numbersort[0] << ", "; 
     cout << numbersort[1] << ", "; 
     cout << numbersort[2] << ", "; 
     cout << numbersort[3] << ", "; 
} 

有誰知道,如果有一種方法使用for或while循環由左到陣列中的號碼重新排列升序排列正確的,而不是僅僅使用3 if語句反正做這個排序算法更高效/更短的C++

+3

這似乎屬於http://codereview.stackexchange.com/ –

+3

最短的解決方法是調用['標準:: sort'(http://en.cppreference.com/w/cpp /算法/排序)。查看鏈接的例子。 – 5gon12eder

+3

如果您想讓某人查看您的代碼,您應該詢問[codereview.se] –

回答

2

你可以使用std ::排序或冒泡排序算法(link how it works)。算法檢查是從下一個更大的循環中的當前數字。如果它改變這些數字在數組中。最後你會得到陣列末端的最大數字,在數組開始時最小。

int main() 
{ 
    int numbersort[] = { 200, 85, 63, 4 }; 
    int temp = 0; 
    // This loop sorts all numbers in the array 
    for (int z = 0; z < 4; ++z) 
    { 
     // This loop sorts only one number to the end 
     for (int i = 0; i < 3; ++i) 
     { 
      if (numbersort[i] > numbersort[i + 1]) 
      { 
       temp = numbersort[i]; 
       numbersort[i] = numbersort[i + 1]; 
       numbersort[i + 1] = temp; 
      } 
     } 
    } 

    cout << "Sorted numbers" << endl; 
    for (int i = 0; i < 4; ++i) 
    { 
     cout << numbersort[i] << endl; 
    } 

    system("pause"); 
    return 0; 
} 
1

事情是這樣的:

i = 0; 
while (i < (sizeof(numbersort)/sizeof(numbersort[0])) - 1) 
{ 
    if (numbersort[i] >= numbersort[i + 1]) 
    { 
    std::swap(numbersort[i], numbersort[i + 1]); 
    i = 0; 
    } 
    else 
    { 
    ++i; 
    } 
}