目录
冒泡排序
通过相邻元素比较交换完成排序
namespace _14
{
internal class Program
{
static void Main(string[] args)
{
string str=Console.ReadLine();
string[] strarr = str.Split(" ");
int[] intarr = new int[strarr.Length];
for (int i = 0; i < intarr.Length; i++)
{
intarr[i]= Convert.ToInt32(strarr[i]);
}
//冒泡排序
for (int i = 0; i < intarr.Length-1; i++)
{
bool f = false;
for (int j = 0; j < intarr.Length - 1 - i; j++)
{
if (intarr[j] < intarr[j + 1])
{
int t=intarr[j];
intarr[j]=intarr[j+1];
intarr[j+1]=t;
f=true;
}
}
if (f == false)
{
break;
}
}
foreach (int item in intarr)
{
Console.WriteLine(item);
}
}
}
}
选择排序
每轮找出最小元素,交换到已排序序列末尾
namespace _14
{
internal class Program
{
static void Main(string[] args)
{
string str=Console.ReadLine();
string[] strarr = str.Split(" ");
int[] intarr = new int[strarr.Length];
for (int i = 0; i < intarr.Length; i++)
{
intarr[i]= Convert.ToInt32(strarr[i]);
}
for (int i = 0; i < intarr.Length - 1; i++)
{
int min = i;
for (int j = i;j< intarr.Length; j++)
{
if(intarr[j]< intarr[min])
{
min = j;
}
int t = intarr[j];
intarr[j] = intarr[min];
intarr[min] = t;
}
}
foreach (int item in intarr)
{
Console.WriteLine(item);
}
}
}
}
快速排序
分治法,选择基准元素分割数组,递归排序,不稳定
public static void QuickSort(int[] arr, int low, int high)
{
if (low < high)
{
int pivot = Partition(arr, low, high);
QuickSort(arr, low, pivot - 1);
QuickSort(arr, pivot + 1, high);
}
}
private static int Partition(int[] arr, int low, int high)
{
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++)
if (arr[j] <= pivot)
(arr[++i], arr[j]) = (arr[j], arr[i]);
(arr[i + 1], arr[high]) = (arr[high], arr[i + 1]);
return i + 1;
}
C#内置排序方法
Array.Sort() / List<T>.Sort()
int[] numbers = { 5, 2, 8, 1 };
Array.Sort(numbers);
List<int> list = new List<int> { 3, 1, 4 };
list.Sort();