数据结构之冒泡排序
定义
冒泡排序:就是将一个数组中的元素按照从大到小或者从小到大的排序进行排列。
比如数组:3,4,2,1,0,5 按照从小到大进行排序。
首先3和4比,如果4大,所以位置不换,4与2比,4大,所以4与2换位置,此时数组为:3,2,4,1,0,5 。依次对比最终结果是3,2,1,0,4,5 这是第一次的结果,后续就是数组3,2,1,0,4之间进行比较,原理同上。
代码实现:
class BubbleSort { /// <summary> /// 排序 升序 /// </summary> /// <param name="arr"></param> public static void Sort(int[] arr) { int n = arr.Length; //第一层循环是因为总共有n个元素 for (int i = 0; i < n - 1; i++) { //n-i-1,之所以还要减去i,是因为已经排好序的元素就不用再比较了,
//因为冒泡排序的规则就已经确定了已经排好序的元素要么做大,要么最小,没必要重复比较。 for (int j = 0; j < n-i-1; j++) { if(arr[j]>arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j + 1] = temp; } } } } } static void Main(string[] args) { int[] arr = { 3, 2, 1, 6 }; BubbleSort.Sort(arr); for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } }
结果:
1
2
3
6
泛型实现
class BubbleSortGeneric { /// <summary> /// 排序 升序 这里必须实现IComparable接口,必须是要可比较的。 /// </summary> /// <param name="arr"></param> public static void Sort<E>(E[] arr) where E:IComparable<E> { int n = arr.Length; //第一层循环是因为总共有n个元素 for (int i = 0; i < n - 1; i++) { //n-i-1,之所以还要减去i,是因为已经排好序的元素就不用再比较了,
//因为冒泡排序的规则就已经确定了已经排好序的元素要么做大,要么最小,没必要重复比较。 for (int j = 0; j < n - i - 1; j++) { if (arr[j].CompareTo(arr[j + 1])>0) { E temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }
调用:
class Program { static void Main(string[] args) { int[] arr = { 3, 2, 1, 6 }; char[] arr2 = {'W','C','A','D','B' }; BubbleSortGeneric.Sort(arr); BubbleSortGeneric.Sort(arr2); for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr2[i]); } } }
结果:
1
2
3
6
A
B
C
D
比较自定义类,自定义一个Date类,重写比较方法
class Date : IComparable<Date> { private int year; private int month; private int day; private string happen; public Date(int year, int month, int day, string happen) { this.year = year; this.month = month; this.day = day; this.happen = happen; } /// <summary> /// 重写比较接口 /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(Date other) { if (this.year > other.year) return 1; if (this.year < other.year) return -1; if (this.month > other.month) return 1; if (this.month < other.month) return -1; if (this.day > other.day) return 1; if (this.day < other.day) return -1; return 0; } public override string ToString() { return year + "/" + month + "/" + day + ":" + happen; } }
调用:
class Program { static void Main(string[] args) { Date[] dates = { new Date(2020,2,1,"ahaha"), new Date(2020,1,25,"春节"), }; BubbleSortGeneric.Sort(dates); for (int i = 0; i < dates.Length; i++) { Console.WriteLine(dates[i]); } } }
结果:
2020/1/25:春节
2020/2/1:ahaha
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术