c#冒泡排序算法

时间:2025-11-19 05:40:52 C语言

c#冒泡排序算法

  C#中如何实现冒泡排序?下面小编为大家整理了c#冒泡排序算法,希望能帮到大家!

  冒泡排序(Bubble Sort)

  冒泡排序算法的运作如下:

  1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。

  2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

  3.针对所有的元素重复以上的步骤,除了最后一个。

  4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

平均时间复杂度

  复制代码 代码如下:

  /pic/

  /pic/ 冒泡排序

  /pic/

  /pic/

  /pic/

  public static void BubbleSort(int[] arr, int count)

  {

  int i = count, j;

  int temp;

  while (i > 0)

  {

  for (j = 0; j < i - 1; j++)

  {

  if (arr[j] > arr[j + 1])

  {

  temp = arr[j];

  arr[j] = arr[j + 1];

  arr[j + 1] = temp;

  }

  }

  i--;

  }

  }

  /pic/p>

  int[] y = new int[] { 1, 32, 7, 2, 4, 6, 10, 8, 11, 12, 3, 9, 13, 5 };

  BubbleSort(y, y.Length );

  foreach (var item in y)

  {

  Console.Write(item+" ");

  }

  /pic/p>

  简单且实用的冒泡排序算法的控制台应用程序。运行界面如下:

  复制代码 代码如下:

  using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Text;

  namespace 冒泡排序

  {

  class Program

  {

  /pic/

  /pic/ 交换两个整型变量的值

  /pic/

  /pic/要交换的第一个整形变量

  /pic/要交换的第一个整形变量

  private static void Reverse(ref int a, ref int b)

  {

  int temp = a;

  a = b;

  b = temp;

  }

  static void Main(string[] args)

  {

  while (true)

  {

  string[] strInput;/pic/p>

  int[] intInput;

  string[] separator = { ",", " " };/pic/p>

  Console.WriteLine("请输入数据,以","或空格分隔,或按"q"退出。");

  string str = Console.ReadLine();/pic/p>

  if (str == "q")

  {

  return;

  }

  strInput = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);/pic/p>

  intInput = new Int32[strInput.Length];

  /pic/p>

  /pic/p>

  try

  {

  for (int i = 0; i < strInput.Length; i++)

  {

  intInput[i] = Convert.ToInt32(strInput[i]);

  }

  }

  catch (FormatException err)

  {

  Console.WriteLine(err.Message);

  }

  catch(OverflowException err)

  {

  Console.WriteLine(err.Message);

  }

  /pic/p>

  for (int i = 0; i < intInput.Length - 1; i++)/pic/p>

  {

  for (int j = 0; j < intInput.Length - i - 1; j++)/pic/p>

  {

  /pic/p>

  /pic/p>

  if (intInput[j] > intInput[j + 1])

  {

  Reverse(ref intInput[j], ref intInput[j + 1]);

  }

  }

  }

  string strOutput = "";/pic/p>

  foreach (int temp in intInput)

  {

  strOutput += Convert.ToString(temp) + ",";

  }

  Console.WriteLine("排序后的数据为:rn{0}rn", strOutput);

  }

  }

  }

  }

【c#冒泡排序算法】相关文章:

c#快速排序算法11-16

C#排序算法之快速排序01-07

C#排序算法之堆排序11-16

C语言冒泡排序算法实例12-19

C++冒泡排序算法实例详解10-13

c语言中冒泡排序、插入排序、选择排序算法比较10-15

快速排序算法及C#版的实现示例12-06

冒泡排序算法原理及JAVA实现代码方法09-26

C语言经典冒泡排序法12-09