C#实现整数冒泡排序、选择排序
????????/// <summary>
??????? /// 交換兩個整數的值
??????? /// </summary>
??????? /// <param name="aa">數1</param>
??????? /// <param name="bb">數2</param>
????private static void Swap(ref int aa,ref int bb)
??????? {
??????????? int temp;
??????????? temp = bb;
??????????? bb = aa;
??????????? aa = temp;
??????? }
?// 冒泡排序
?? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? int[] a={1,2,5,7,9,8,10,6,4,3};
??????????? BubbleSort(a);
??????????? for (int i = 0; i < a.Length; i++)
??????????????? Console.Write(a[i] + " ");
??????????? Console.ReadKey();
??????? }
?/// <summary>
??????? /// 冒泡排序
??????? /// </summary>
??????? /// <param name="a">傳入要排序的數組</param>
??????? private static void BubbleSort(int[] a)
??????? {
??????????? for (int i = 0; i < a.Length - 1; i++)
??????????? {
??????????????? for (int j = 0; j < a.Length - i - 1; j++)
??????????????? {
??????????????????? if (a[j] < a[j + 1])//降序排列
??????????????????? {
??????????????????????? Swap(ref a[j], ref a[j + 1]);
??????????????????? }
??????????????? }
??????????? }
??????? }
???}
//選擇排序
?class Program
?{
??????? static void Main(string[] args)
??????? {
??????????? int[] a = { 1, 2,? 4, 3,6,5,7,9,8 };
??????????? SelectionSort(a);
??????????? for (int i = 0; i < a.Length; i++)
??????????????? Console.Write(a[i] + " ");
??????????? Console.ReadKey();
??????? }
??????? /// <summary>
??????? /// 選擇排序
??????? /// </summary>
??????? /// <param name="a">傳入要排序的數組</param>
??????? private static void SelectionSort(int[] a)
??????? {
??????????? int k;
??????????? for (int i = 0; i < a.Length - 1; i++)
??????????? {
??????????????? k = i;
??????????????? for (int j = i+1; j < a.Length ; j++)
??????????????? {
??????????????????? if (a[j] < a[k])//升序排列
??????????????????? {
??????????????????????? k = j;
??????????????????????
??????????????????? }
??????????????? }
??????????????? if(k!=i)
??????????????????? Swap(ref a[i], ref a[k]);
??????????? }
??????? }
?????}
--摘自zhouhb
轉載于:https://www.cnblogs.com/wangliqiang1026/p/4332068.html
總結
以上是生活随笔為你收集整理的C#实现整数冒泡排序、选择排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《黑马程序员》 流程控制(C语言)
- 下一篇: codeforces 337D Book