2017-05-17 41 views
0

我正在用C++對數組進行排序,0被打印在第一個索引上,最高值被忽略。我的錯在哪裏?這是我的代碼。 我的邏輯有問題嗎?我對C++很陌生,如果我做錯了,我很抱歉。當在C++中排序數組時,第一個元素變爲0

#include<iostream> 
#include<fstream> 
#include<cstdlib> 
using namespace std; 
int main() 
{ 
    int *x, size, temp; 
    cout << "Enter the size of array\n"; 
    cin >> size; 
    x = new int[size]; 
    for (int i = 0; i < size; i++) 
    { 
     cin >> x[i]; 
    } 
    cout << "\nData before sorting: "; 
    for (int j = 0; j < size; j++) 
    { 
     cout << x[j] << ' '; 
    } 
    for (int i = 0; i < size; i++) 
    { 
     for (int j = 0; j < size; j++) 
     { 
      if (x[j] > x[j + 1]) 
      { 
       temp = x[j]; 
       x[j] = x[j + 1]; 
       x[j + 1] = temp; 
      } 
     } 
    } 
    cout << "\nData after sorting: "; 
    for (int j = 0; j < size; j++) 
    { 
     cout << x[j] << ' '; 
    } 
} 
+2

您是否嘗試過使用調試器進行調試? – Stefan

+3

'j

+0

@Stefan調試器完成0狀態。 –

回答

0

與變化的工作代碼是

#include<iostream> 
#include<fstream> 
#include<cstdlib> 
using namespace std; 
int main() 
{ 
    int *x, size, temp; 
    cout << "Enter the size of array\n"; 
    cin >> size; 
    x = new int[size]; 
    for (int i = 0; i < size; i++) 
    { 
     cin >> x[i]; 
    } 
    cout << "\nData before sorting: "; 
    for (int j = 0; j < size; j++) 
    { 
     cout << x[j] << ' '; 
    } 
    for (int i = 0; i < size; i++) 
    { 
     for (int j = 0; j < size-1; j++) 
     { 
      if (x[j] > x[j + 1]) 
      { 
       temp = x[j]; 
       x[j] = x[j + 1]; 
       x[j + 1] = temp; 
      } 
     } 
    } 
    cout << "\nData after sorting: "; 
    for (int j = 0; j < size; j++) 
    { 
     cout << x[j] << ' '; 
    } 
    cin >> temp; 
} 

改變「大小」爲「尺寸1」循環語句,以避免訪問未分配的陣列成員

0

的用於循環應糾正以便j運行至size - 1 & i運行至size。否則,您會在不必要的比較中吞噬一個數字,並在某些情況下顯示零或垃圾數量。

以下for循環替換到您的程序修復您的問題。

for(int i=0;i<size;i++) 
{ 
    for(int j=0;j<size-1;j++) 
    { 
     if(x[j]>x[j+1]) 
     { 
      temp=x[j]; 
      x[j]=x[j+1]; 
      x[j+1]=temp; 
     } 
    } 
} 
相關問題