冒泡排序算法
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; public partial class Bubble : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int[] arrayNum = new int[10]; arrayNum[0] = 100; arrayNum[1] = 20; arrayNum[2] = 80; arrayNum[3] = 56; arrayNum[4] = 98; arrayNum[5] = 1; arrayNum[6] = 6; arrayNum[7] = 9; arrayNum[8] = 23; arrayNum[9] = 21; arrayNum = BubbleSort(arrayNum); //调用排序算法 string str = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}"; str = string.Format(str, arrayNum[0], arrayNum[1], arrayNum[2], arrayNum[3], arrayNum[4], arrayNum[5], arrayNum[6], arrayNum[7], arrayNum[8], arrayNum[9]); Response.Write(str); } /// <summary> /// 冒泡排序算法 /// </summary> /// <param name="arrayNum">要排序的数组</param> /// <returns></returns> private int[] BubbleSort(int[] arrayNum) { return SortMethod(arrayNum); } private static int[] SortMethod(int[] arrayNum) { int i, j, k;//k为临时寄存器 bool exchange;//交换标志 for (i = 1; i < arrayNum.Length; i++) { exchange = false; for (j = arrayNum.Length - 1; j >= i; j--) { if (arrayNum[j - 1] > arrayNum[j]) { k = arrayNum[j]; arrayNum[j] = arrayNum[j - 1]; arrayNum[j - 1] = k; exchange = true; } } if (!exchange) { break; } } return arrayNum; } }