2011-09-04 69 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--) 

这是建立你堆。您从第二层到最后一层儿童开始,一直移动到树的顶部节点。