62,046
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//需要引入Text这个命名空间
using System.Text;
public partial class maopaopaixu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSort_Click(object sender, EventArgs e)
{
//交换时的变量
int mytemp;
//取得输入文本框的值
string sortNum = this.TextBox1.Text;
//根据,号分割字符串为字符数组
string[] array1 = sortNum.Split(',');
//取得数组长度
int count = array1.Length;
//将字符数组转换成整型数组
int[] array2 = new int[count];
for (int i = 0; i < count; i++)
{
array2[i] = Convert.ToInt32(array1[i]);
}
//执行从小到大的排序
for (int m = 0; m < count; m++)
{
for (int n = m - 1; n >= 0; n--)
{
if (array2[n] > array2[n + 1])
{
mytemp = array2[n];
array2[n] = array2[n+1];
array2[n+1] = mytemp;
}
}
}
//打印出排序后的结果
Response.Write("排序结果为:");
for (int k = 0; k < count; k++)
{
Response.Write(array2[k]+" ");
}
}
}
class Program
{
public class SwapObj
{
public static void swap<T>(ref T a, ref T b)
{
T c;
c=a;
a=b;
b=c;
}
}
static void Main(string[] args)
{
//冒泡排序:
int[] num = new int[] { 12, 3, 6, 16, 19, 7, 33, 21, 20, 100, 100, 115, 55, 58, 77};
foreach (int i in num)
{
Console.Write(i.ToString() + ", ");
}
Console.WriteLine();
Console.WriteLine("排序后:");
int counter1 = 0;
int counter2 = 0;
for(int i=0; i<num.Length-1;i++)
{
for(int j=i+1; j<num.Length; j++)
{
if(num[i]<num[j])
{
SwapObj.swap<int>(ref num[i], ref num[j]);
counter1++;
}
counter2++;
}
}
Console.WriteLine( "循环了{0}次。", counter2);
Console.WriteLine("其中交换了{0}次。", counter1);
foreach (int i in num)
{
Console.Write(i.ToString() + ", ");
}
Console.ReadLine();
}
}