不断的进行比较讲大的元素放在后面。
//冒泡排序 O(n²)
class BubbleSort
{
public static void Sort(int[] arr)
{
int n = arr.Length;
//外层循环控制冒泡次数
for (int i = 0; i < n; i++)
{
//减去i 不需要对已经排好序的元素再次进行比较
//内层循环在数组[0...n-1-i]范围内冒泡最大值
//j取值范围[0...n-1-i) j+1取值范围[1...n-1-i]
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
Swap(arr, j, j + 1);
}
}
}
//交换数组中索引i和j对应元素的位置
private static void Swap(int[] arr, int i, int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
泛型冒泡排序
//泛型冒泡排序
class BubbleSortGeneric
{
//支持任意可比较的数据类型排序
public static void Sort<E>(E[] arr) where E:IComparable<E>
{
int n = arr.Length;
//外层循环控制冒泡次数
for (int i = 0; i < n; i++)
{
//减去i 不需要对已经排好序的元素再次进行比较
for (int j = 0; j < n - 1 - i; j++)
{
//根据CompareTo方法比较大小
if (arr[j].CompareTo(arr[j + 1])>0)
Swap(arr, j, j + 1);
}
}
}
private static void Swap<E>(E[] arr, int i, int j)
{
E t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
在此用string类型组成的Data类型来进行比较,新建一个Data类
//日期类
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;
}
//自定义比较方法。
public int CompareTo(Date other)
{
if (this.year > other.year) return 1; //年份大的返回1,放后面
if (this.year < other.year) return -1; //年份小的返回-1,放前面
if (this.month > other.month) return 1; //月份大的返回1,放后面
if (this.month < other.month) return -1; //月份小的返回-1,放前面
if (this.day > other.day) return 1; //天数大的返回1,放后面
if (this.day < other.day) return -1; //天数小的返回-1,放前面
return 0; //年月日都相等返回0,相邻放一起
}
public override string ToString()
{
return year + "/" + month + "/" + day + ": " + happen;
}
}
这里重写CompareTo函数可以借鉴一下。
Main函数
class Program
{
static void Main(string[] args)
{
int[] a = { 4, 3, 5, 2, 1, 0 };
char[] a2 = { 'C', 'A', 'D', 'B', 'G', 'F', 'E'};
float[] a3 = { 0.21f, 0.10f, 0.78f, 0.15f, 0.17f };
Date[] dates =
{
new Date(2020,7,7,"七夕节"),
new Date(2020,8,15,"中秋节"),
new Date(2020,1,1,"元旦节"),
new Date(2020,3,8,"妇女节"),
new Date(2020,4,4,"清明节"),
new Date(2020,5,1,"劳动节"),
new Date(2020,9,10,"教师节"),
new Date(2020,1,25,"春节"),
new Date (2020,2,14,"情人节"),
new Date(2020,10,1,"国庆节"),
new Date(2020,12,25,"圣诞节"),
new Date(2020,6,1,"儿童节")
};
BubbleSortGeneric.Sort(dates);
for (int i = 0; i < dates.Length; i++)
Console.WriteLine(dates[i]);
Console.Read();
}
}
比较结果