c# 冒泡排序算法(Bubble Sort) 附实例代码
冒泡排序(Bubble Sort)
冒泡排序算法的运作如下:
1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3.针对所有的元素重复以上的步骤,除了最后一个。
4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
平均时间复杂度 |
---|
/// <summary>
/// 冒泡排序
/// </summary>
/// <param name="arr"></param>
/// <param name="count"></param>
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--;
}
}
//使用例子
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+" ");
}
//1 2 3 4 5 6 7 8 9 10 11 12 13 32
简单且实用的冒泡排序算法的控制台应用程序。运行界面如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace 冒泡排序
{
class Program
{
/// <summary>
/// 交换两个整型变量的值
/// </summary>
/// <param name="a">要交换的第一个整形变量</param>
/// <param name="b">要交换的第一个整形变量</param>
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;//用来接收用户输入的字符串
int[] intInput;
string[] separator = { ",", " " };//设置分隔符
Console.WriteLine("请输入数据,以\",\"或空格分隔,或按\"q\"退出。");
string str = Console.ReadLine();//接收键盘输入
if (str == "q")
{
return;
}
strInput = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);//将用户输入的字符串分割为字符串数组
intInput = new Int32[strInput.Length];//将字符串数组的每一个元素转换为整型变量
//转换时如果出现格式错误或溢出错误则提示
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);
}//排序算法主体
for (int i = 0; i < intInput.Length - 1; i++)//这里的Length要减1否则会超界
{
for (int j = 0; j < intInput.Length - i - 1; j++)//这里的Length要减i以减少重复运算
{
//如果元素j比它之后的一个元素大,则交换他们的位置
//如此循环直到遍历完整个数组
if (intInput[j] > intInput[j + 1])
{
Reverse(ref intInput[j], ref intInput[j + 1]);
}
}
}string strOutput = "";//用于输出的字符串
foreach (int temp in intInput)
{
strOutput += Convert.ToString(temp) + ",";
}
Console.WriteLine("排序后的数据为:\r\n{0}\r\n", strOutput);
}
}
}
}
您可能感兴趣的文章:
- C# 调用存储过程简单完整的实例代码
- C#中通过API实现的打印类 实例代码
- 应用程序唯一运行实例C#代码实现(转)
- C#连接Access2007数据库代码实例完整版
- C#动态执行字符串(动态创建代码)的实例代码
- C#编写的艺术字类实例代码
- 使用C#实现读取系统配置文件的代码实例讲解
- C#中把Datatable转换为Json的5个代码实例
- C#调用Quartz实例代码
- C# 大小写转换(金额)实例代码
- C# 调用Delphi dll 实例代码
- C#装饰者模式实例代码
- C#使用MailAddress类发送html格式邮件的实例代码
- C#调用WORD处理的实例代码(包含excel)
- C#实现json的序列化和反序列化实例代码
- c#代码自动修改解决方案下任意文件实例
- 利用thrift实现js与C#通讯的实例代码
- C#新手入门代码 命名空间嵌套,各空间内成员相互独立的实例
- C#中把Datatable转换为Json的5个代码实例
- 在c#中使用servicestackredis操作redis的实例代码