冒泡排序
不断对相邻两个元素进行比较并交换位置,有几个元素则需要重复进行几次冒泡操作
冒泡排序的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sorting
{
class BubbleSort
{
public static void Sort(int[] arr)
{
int n = arr.Length;
for(int i=0;i<n;i++)//重复次数
{
//减去i 不需要对已经排好序的元素再次进行比较
for(int j=0;j<n-1-i;j++)//冒泡操作
{
if(arr[j]>arr[j+1])
{
Swap(arr, j, j + 1);
}
}
}
}
private static void Swap(int[]arr,int i,int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
主函数调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sorting
{
class Program
{
static void Main(string[] args)
{
int[] a = {
4, 3, 5, 2, 1, 0 };
BubbleSort.Sort(a);
for (int i = 0; i < a.Length; i++)
Console.Write(a[i]+"\t");
Console.ReadLine();
}
}
}
结果:
0 1 2 3 4 5
冒泡排序支持泛型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sorting
{
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++)//冒泡操作
{
if (arr[j].CompareTo(arr[j + 1])>0)
{
Swap(arr, j, j + 1);
}
}
}
}
private static void Swap<E>