我目前正在尝试实现二进制排序逻辑。我首先生成随机数。然后创建该数组的副本,然后使用二进制排序方法对其进行排序。问题是排序不能正常工作。我不确定我的比较是否正确。任何想法为什么不能正确排序?
namespace binarySort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Stopwatch sw = new Stopwatch();
Random r = new Random();
OpenFileDialog open1 = new OpenFileDialog();
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
public void RandomNumber()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
for (int i = 0; i < size; i++)
{
createArray[i] = r.Next(1, max);
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Random" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void BinarySort()
{
operations = 0;
sw.Reset();
sw.Start();
int low = 0;
int high = 0;
int temp = 0;
int mid = 0;
for (int i = 0; i < size; i++)
{
copyArray[i] = createArray[i];
}
for (int i = 1; i < size; i++)
{
high = i - 1;
temp = copyArray[i];
while (low <= high)
{
operations++;
mid = (low + high) / 2;
if (temp < copyArray[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
operations++;
for (int j = i - 1; j >= low; j--)
{
copyArray[j + 1] = copyArray[j];
}
copyArray[low] = temp;
}
for (int i = 0; i < size; i++)
{
sortArray[i] = copyArray[i];
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Binary Insertion" + Environment.NewLine + Environment.NewLine);
DisplaySorted();
}
private void buttonSortArray_Click(object sender, EventArgs e)
{
BinarySort();
}
}
}
例如: