c#实验一:基于winform的冒泡排序练习

时间:2023-03-09 00:30:20
c#实验一:基于winform的冒泡排序练习

一、界面设计

c#实验一:基于winform的冒泡排序练习

在排序前textbox中输入数字,以逗号隔开,通过两个button实现降序排序或升序排序,然后在排序后textbox中显示

三个关键点:

1、监测输入是否合法,最好使用正则表达式

2、拆分textbox中字符串,使用String类的slipt方法

3、冒泡排序法

二、关于拆分textbox中字符串

1、如果以空格作为字符串结束标志,应采用以下语句

string str = textBox1.Text.Trim();
string[] ss = str.Split();

2、如果以逗号作为结束标志,应采用以下语句

string str = textBox1.Text.Trim();     或者 string str = textBox1.Text;
string[] ss = str.Split(',');

三、冒泡排序法

冒泡排序法就是把数组中的元素按从小到大或从大到小顺序排例,注意每次比较的次数依次减小

公式格式为:

 for(int i = ; i < array.length - ; i++)
{
for(int j = ; j < array.length - - i; j++) //不能忘减i
{
int temp;
if(array[j] < array[j + ])
{
temp = array[j]; //这里决定了是降序,还是升序
array[j] = array[j + ] ;
array[j + ] =temp;
}
}
}

四、完整代码:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions; namespace 冒泡法排序
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button2_Click(object sender, EventArgs e) //降序排列
{
string str = textBox1.Text.Trim();
//string str = textBox1.Text;
string[] ss = str.Split(); string temp = "";
for (int i = ; i < ss.Length - ; i++)
{
for (int j = ; j < ss.Length - - i; j++)
{
if (int.Parse(ss[j]) < int.Parse(ss[j + ]))
{
temp = ss[j];
ss[j] = ss[j + ];
ss[j + ] = temp;
}
}
}
for (int i = ; i < ss.Length; i++)
{
textBox2.AppendText(ss[i]);
textBox2.AppendText(",");
}
} private void button1_Click(object sender, EventArgs e) //升序排例
{
string str = textBox1.Text.Trim();
//string str = textBox1.Text;
string[] ss = str.Split(','); string temp = "";
for (int i = ; i < ss.Length - ; i++)
{
for (int j = ; j < ss.Length - - i; j++)
{
if (int.Parse(ss[j]) > int.Parse(ss[j + ]))
{
temp = ss[j];
ss[j] = ss[j + ];
ss[j + ] = temp;
}
}
}
for (int i = ; i < ss.Length; i++)
{
textBox2.AppendText(ss[i]);
textBox2.AppendText(",");
}
} private void Form1_Load(object sender, EventArgs e)
{
int[] array = { , , , , , , , , , , , , , , , , , }; for (int i = ; i < array.Length - ; i++)
{
for (int j = ; j < array.Length - -i; j++)
{
if (array[j] <= array[j + ])
{
int temp = array[j];
array[j] = array[j + ]; //把大的放在前面
array[j + ] = temp; //小的放在后面
}
}
} //for (int ik = 0; ik < array.Length; ik++)
//{
// textBox2.AppendText(array[ik].ToString());
// textBox2.AppendText(",");
//}
foreach(int i in array)
{
textBox2.AppendText(i.ToString());
textBox2.AppendText(",");
}
} private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
}
}
}