我想創建3個線程進行3種排序(冒泡排序,快速排序&合併排序)以快速顯示哪種函數排序?爲了顯示這個我做了3個按鈕陣列(對於每個func。1 arr)&我想用它們的高度對它們進行排序。但我有2個重要問題: 1-如何在運行時顯示交換和按鈕更改?該表單將在排序完成後顯示,但我希望在運行時看到這些更改。我不能和線程一起運行排序併發。顯示運行時間和線程上的表格變化
現在這是我的代碼:
命名空間threade {
public partial class Form1 : Form
{
Button[] btns1;
Button[] btns2;
Button[] btns3;
public Form1()
{
InitializeComponent();
btns1 =new Button[] { button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16};
btns2 = new Button[] { button17, button18, button19, button20, button21, button22, button23, button24, button25, button26, button27, button28, button29, button30, button31, button32 };
btns3 = new Button[] { button33, button34, button35, button36, button37, button38, button39, button40, button41, button42, button43, button44, button45, button46, button47, button48 };
foreach (Button btn in btns1)
{
btn.Text = btn.Size.Height.ToString();
}
foreach (Button btn in btns2)
{
btn.Text = btn.Size.Height.ToString();
}
foreach (Button btn in btns3)
{
btn.Text = btn.Size.Height.ToString();
}
Thread t1 = new Thread(new ThreadStart(sort1));
Thread t2 = new Thread(new ThreadStart(sort2));
Thread t3 = new Thread(new ThreadStart(sort3));
}
void sort1() {
bsort(btns1, 16);
}
void sort2()
{
qsort(0, 15, btns2);
}
void sort3()
{
mgsort(0, 15, btns3);
}
Button aa = new Button(); Button aa2 = new Button();
void swap(int i,int j,Button[]btns)
{
aa = btns[i];
btns[i] = btns[j];
btns[j] = aa;
int t = btns[i].Location.X;
btns[i].Location = new Point(btns[j].Location.X, btns[i].Location.Y);
btns[j].Location = new Point(t, btns[j].Location.Y);
}
int part(int l, int h,Button[] btns)
{
int i, j=l;
int p = btns[l].Size.Height;
for (i = l +1; i <= h; i++)
if (btns[i].Size.Height < p)
{
j++;
swap(i, j, btns);
}
int s = j;
swap(l, j, btns);
return s;
}
void qsort(int l, int h, Button[] btns)
{
if (h > l)
{
int p = part(l, h, btns);
qsort(l, p-1,btns);
qsort(p+1, h,btns);
}
}
void bsort(Button[] btns,int n)
{
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if (btns[j].Size.Height < btns[i].Size.Height)
{
aa2 = btns[i];
btns[i] = btns[j];
btns[j] = aa2;
int t = btns[i].Location.X;
btns[i].Location = new Point(btns[j].Location.X, btns[i].Location.Y);
btns[j].Location = new Point(t, btns[j].Location.Y);
Thread.Sleep(10);
}
}
}
使用** ['BackgroundWorker'(http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)**,而不是創建自己的線程。更容易,更容易出錯。 – 2011-04-17 06:47:31
@Cody Grey:使用TPL與Task.CreateNew() – GregC 2011-04-17 06:51:28
@Greg還有其他好處:好的。根據問題中顯示的代碼,這些好處是什麼? – 2011-04-17 06:52:24