C#:冒泡排序演算法

來源:互聯網
上載者:User

標籤:結果   div   變數   new   public   asc   參考型別   adk   foreach   

註:int[] 數組為參考型別

 1 namespace demo 2 { 3     public class Program 4     { 5         static void Main(string[] args) 6         { 7             //原數組 8             int[] nums = new int[] { 12, 10, 4, 8, 1, 3, 2, 9, 5, 6, 18 }; 9             Console.Write("原數組:");10             foreach (int n in nums)11                 Console.Write($"{n} ");12 13             //升序14             BubbleSortAsc(nums);15             Console.Write("\n小->大:");16             foreach (int n in nums)17                 Console.Write($"{n} ");18 19             //降序20             BubbleSortDesc(nums);21             Console.Write("\n大->小:");22             foreach (int n in nums)23                 Console.Write($"{n} ");24             Console.ReadKey();25         }26         /// <summary>27         /// 從小到大排序(使用中間變數)28         /// </summary>29         static void BubbleSortAsc(int[] nums)30         {31             int tmp;32             for(int i=0;i<nums.Length;i++)33             {34                 for(int j=i+1;j<nums.Length;j++)35                 {36                     if(nums[j]<nums[i])37                     {38                         tmp = nums[i];39                         nums[i] = nums[j];40                         nums[j] = tmp;41                     }42                 }43             }44         }45         /// <summary>46         /// 從大到小排序47         /// </summary>48         static void BubbleSortDesc(int[] nums)49         {50             for(int i=0;i<nums.Length;i++)51             {52                 for(int j=i+1;j<nums.Length;j++)53                 {54                     if(nums[i]<nums[j])55                     {56                         nums[i] = nums[i] + nums[j];57                         nums[j] = nums[i] - nums[j];  58                         nums[i] = nums[i] - nums[j];59                     }60                 }61             } 62         }63     }64 }

執行結果:

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.