冒泡排序 ( C# 向)

來源:互聯網
上載者:User

標籤:冒泡排序   排序演算法   

冒泡排序是 一種比較簡單的排序演算法,其核心邏輯就是不斷地比較相鄰的兩個數,如果前數 大於 後數,就把 兩個數交換。 這樣一趟比較下來,確保把最小的數字移動到了數列開始位置,或者把最大的數字移動到了數列的結尾位置。

轉自http://blog.csdn.net/huutu http://www.thisisgame.com.cn



代碼如下:

轉自http://blog.csdn.net/huutu http://www.thisisgame.com.cn

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace bubble_sort{    class Program    {        static int calCount = 0;        static void Bubble_Sort(ref int[] intArr)        {            for (int outside = 0; outside < intArr.Length-1; outside++)            {                for (int index = 0; index < intArr.Length-1-outside; index++)                {                    calCount++;                    //如果前一個大於後一個,交換兩個值;                    if (intArr[index] > intArr[index + 1])                    {                        intArr[index] = intArr[index] + intArr[index + 1];                        intArr[index + 1] = intArr[index] - intArr[index + 1];                        intArr[index] = intArr[index] - intArr[index + 1];                                            }                }            }        }        static void Main(string[] args)        {            int[] intArr = new int[10] { 51, 41, 31, 91, 81, 71, 61, 21, 11, 0 };            Console.Write("排序前:");            for (int i = 0; i < intArr.Length; i++)            {                Console.Write(intArr[i]+" ");            }            Console.WriteLine();            Bubble_Sort(ref intArr);            Console.Write("排序後:");            for (int i = 0; i < intArr.Length; i++)            {                Console.Write(intArr[i] + " ");            }            Console.WriteLine();            Console.WriteLine("計算次數:" + calCount);            Console.ReadLine();        }    }}
轉自http://blog.csdn.net/huutu http://www.thisisgame.com.cn

轉自http://blog.csdn.net/huutu http://www.thisisgame.com.cn

冒泡排序 ( C# 向)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.