C#——设计窗体程序,输入一串字符数字用逗号分隔,对该串进行排序输出
1.设计界面
2.编写代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 排序
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//第一种排序方式——冒泡排序
/*
private void button1_Click(object sender, EventArgs e)
{
string[] sources = textBox1.Text.Split(',');
int[]a=new int[sources.Length];
for (int i = 0; i < sources.Length;i++ )
{
a[i] = Convert.ToInt32(sources [i]); //将字符串数组中的每个数字转换为整数
}
for (int i = 1; i < a.Length; i++) //冒泡排序
{
for (int j = 1; j <= a.Length-i;j++ )
{
if(a[j-1]>a[j])
{
int t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
* */
//第二种排序方式
private void button1_Click(object sender, EventArgs e)
{
string[] sources = textBox1.Text.Split(',');
int[]a=new int[sources .Length];
for (int i = 0; i < sources.Length; i++)
{
a[i] = Convert.ToInt32(sources[i]); //将字符串数组中的每个数字转换为整数
}
for (int i = 0; i < a.Length-1;i++ )
{
for (int j = i; j < a.Length;j++ )
{
if(a[j]>a[i])
{
int t = a[j];
a[j] = a[i];
a[i] = t;
}
}
}
label2.Text = "排序后的序列是:";
foreach (int t in a) //依次输出排序后的元素
{
label2.Text += string.Format("{0,-4:D}",t);
}
textBox1.Text = "";
}
}
}
3.运行结果