2011-09-04 68 views
1

我現在正在堆排序。我迄今爲止的代碼有錯誤的輸出。例如,我輸入了4 3 5 2 1,我輸入的第一個數字始終位於最後一個索引處。輸出將是1 2 3 5 4.任何想法我的代碼有什麼問題。堆排序問題

int[] nums = new int[100]; 
    int SizeNum; 
    int x; 
    int currentPass; 
    int nPass = 1; 

    private void ExeButton_Click(object sender, EventArgs e) 
    { 
      nPass = 1; 
      string[] numsInString = EntNum.Text.Split(' '); //split values in textbox 
      for (int j = 0; j < numsInString.Length; j++) 
      { 
       nums[j] = int.Parse(numsInString[j]); 
      } 
      if (SizeNum == numsInString.Length) 
      { 
       SortArray(currentPass); 
       ResultText.AppendText("\n\n"); 
      } 
     } 
    } 

    public void SortArray(int currentPass) 
    { 
     int i; 
     int temp; 
     for (i = (SizeNum/2) - 1; i >= SizeNum; i--) 
      { 
       siftDown(i, x, currentPass + 1); 
      } 

      for (i = SizeNum - 1; i >= 1; i--) 
      { 
       temp = nums[0]; 
       nums[0] = nums[i]; 
       nums[i] = temp; 
       siftDown(0, i - 1, currentPass + 1); 
       Display(currentPass); 
      } 
      Display(currentPass); 
     }   

    public void siftDown(int root, int bottom, int currentPass) 
    { 
     bool done = false; 
     int maxChild; 
     int temp; 

     while ((root * 2 <= bottom) && (!done)) 
     { 
      if (root * 2 == bottom) 
       maxChild = root * 2; 
      else if (nums[root * 2] > nums[root * 2 + 1]) 
       maxChild = root * 2; 
      else 
       maxChild = root * 2 + 1; 
      Display(currentPass); 
      if (nums[root] < nums[maxChild]) 
      { 
       temp = nums[root]; 
       nums[root] = nums[maxChild]; 
       nums[maxChild] = temp; 
       root = maxChild; 
      }     
      else 
      { 
       done = true; 
      }    
     } 
     Display(currentPass); 
    } 

    public void Display(int currentPass) 
    { 
     int i; 
     String numbers = ""; 
     ResultText.AppendText("Pass " + nPass + ": "); 
     for (i = 0; i < SizeNum; i++) 
     numbers += nums[i].ToString() + " , "; 
     ResultText.AppendText(numbers + "\n"); 
     nPass++; 
    } 
+4

您是否嘗試過在代碼上設置斷點並進行調試? –

回答

1

的一個問題是在這一行:

if (SizeNum == numsInString.Length) 

由於SizeNum場沒有初始化,它的值是默認的,即0
因此,當您插入"5 4 3 2 1"numsInString.Length相等5,然後未達到if中的代碼。
事實上,如果你設置SizeNum = numsInString.Length你的代碼似乎工作。

無論如何,正如其他用戶所指出的那樣,如果您使用的是像Visual Studio或sharp-develop這樣的IDE,則應該使用調試器,它對於查找代碼問題確實很有幫助。

這裏有一個如何做的Visual Studio:http://msdn.microsoft.com/en-us/library/sc65sadd.aspx

0

首先對SortArray的循環應該是

for (i = (SizeNum/2) - 1; i >= 0; i--) 

這是建立你堆。您從第二層到最後一層兒童開始,一直移動到樹的頂部節點。