本文介绍了合并排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好
我想用c#.net
实现合并排序但是我有问题
我编写了一个无法运行的程序,但找不到问题
请帮我:((
textbox1
Hello
I want to implement merge sort with c#.net
But I have a problem
I wrote a program that does not run and I cannot find the problem
Please help me :((
textbox1
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int i = 0;
List<int> lst = new List<int>();
if (e.KeyChar == Convert.ToChar(Keys.Enter) && i < 10)
{
lst.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
i++;
}
}
buttom1
buttom1
private void button1_Click(object sender, EventArgs e)
{
List<int> lst = new List<int>();
int[] array = lst.ToArray();
DoSort(array);
}
呼叫合并排序
call merge sort
private void DoSort(int[] array)
{
MergeSorter ms = new MergeSorter(array);
Func<int[]> del = new Func<int[]>(ms.sortArray);
del.BeginInvoke(new AsyncCallback(SortCallback), null);
}
private void SortCallback(IAsyncResult ar)
{
AsyncResult result = (AsyncResult)ar;
Func<int[]> del = (Func<int[]>)result.AsyncDelegate;
try
{
int[] array = del.EndInvoke(ar);
this.textBox1.Invoke(new MethodInvoker(
delegate()
{
string[] sArray = array.ToList().ConvertAll<string>(Convert.ToString).ToArray();
textBox1.Text = string.Join(", ", sArray);
}));
}
catch (Exception ex)
{
this.textBox1.Invoke(new MethodInvoker(delegate()
{
textBox1.Text = "Error sorting array: " + Environment.NewLine + ex.Message;
}));
}
}
合并排序
merge sort
public class MergeSorter {
private int[] a;
private int x;
private MergeSorter()
{
}
public MergeSorter(int[] array)
:this()
{ this.a = array;
this.x = array.Length; }
public int[] sortArray()
{ q_sort(0, x - 1); return a; }
private void q_sort(int left, int right)
{
int pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = a[left];
while
(left < right)
{ while ((a[right] >= pivot) && (left < right))
{ right--; }
if (left != right)
{ a[left] = a[right];
left++; }
while ((a[left] <= pivot) && (left < right))
{ left++; }
if (left != right)
{ a[right] = a[left]; right--; }
}
a[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
{ q_sort(left, pivot - 1); }
if (right > pivot)
{ q_sort(pivot + 1, right); }
}
}
推荐答案
List<int> lst = new List<int>();
并将您的事件修改为,
and modify your events as,
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int i = 0;
if (e.KeyChar == Convert.ToChar(Keys.Enter) && i < 10)
{
lst.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
i++;
}
}
和
and
private void button1_Click(object sender, EventArgs e)
{
int[] array = lst.ToArray();
DoSort(array);
}
它现在正在工作...
希望对您有所帮助.
it''s working now...
Hope it helps..
这篇关于合并排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!