我現在正在堆排序。我迄今爲止的代碼有錯誤的輸出。例如,我輸入了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++;
}
您是否嘗試過在代碼上設置斷點並進行調試? –