排序算法基础篇交换排序之冒泡排序
2016-06-14
<span style="font-family:KaiTi_GB2312;font-size:24px;">namespace Bubble_Sort { class Program { static void Main(string[] args) { int temp = 0; int[] bubleSortAry = { 56, 211, 108, 19, 63, 168, 121, 148, 172, 6, 213, 12312, 2323, 342, 345, 4536, 5634634, 32423, 324244, 168, 121, 13, 187, 77, 148, 205, 123123, 12312, 123232, 43434 ,123,343432,786,567,45654,213,43253252,654654,32432,32}; //声明需要进行排序的数组 #region 排序之前的数组 foreach (int item in bubleSortAry ) //遍历未进行排序之前的数组 { Console.WriteLine(item +""); } Console.WriteLine(); #endregion #region 检测时间开始计时 long timeStart = DateTime.Now.Ticks; //1 ticks=100纳秒=0.1微妙 #endregion #region 冒泡代码 for (int i = 0; i < bubleSortAry.Length; i++) //外循环 { #region 将大的数字移到数组的bubleSortAry.Length-1-i for (int j = 0; j < bubleSortAry.Length-1-i ; j++) //内循环循环,遍历 { if (bubleSortAry[j ]>bubleSortAry[j+1]) //交换值 { temp = bubleSortAry[j + 1]; bubleSortAry[j + 1] = bubleSortAry[j]; bubleSortAry[j] = temp; } } #endregion } long timeEnd = DateTime.Now.Ticks; //排序计时结束 long timeCount = timeEnd - timeStart; //排序经过的时间 #endregion #region 输出 Console.WriteLine(); foreach (int item in bubleSortAry ) //遍历输出排序结果 { Console.Write(item +"///"); } Console.WriteLine(); Console.WriteLine("排序计时"+timeCount/10+"微秒"); #endregion Console.ReadKey(true); } } } </span>
冒泡就先到这里,感觉自己对Bublle Sort还是懵懵懂懂,继续努力吧。另外有两个遗留问题:
1、为什么数组中元素较少时,不能很好的检测排序用时呢?
2、为什么程序第二次排序用时有时会为0?
感谢您的宝贵时间,祝您生活愉快~
—joker