Я сейчас работаю над сортировкой кучи.Коды, которые у меня пока есть, имеют неправильный вывод.Например, я ввел 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++;
}