------冒泡排序
private static void MaoPaoSort()
{
int[] array = new int[5] { 4, 5, 10, 6, 7 };
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = array.Length - 1; j > i; j--)
{
if (array[j] < array[j - 1])
{
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
}
---------选择排序
private static void SortNum()
{
int[] array = new int[5] { 4, 5, 10, 6, 7 };
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
}
---------选择排序(优化后)
private static void SortNum()
{
int[] array = new int[5] { 4, 5, 10, 6, 7 };
for (int i = 0; i < array.Length - 1; i++)
{
//寻找最小数值的下标与第一位交换
int minIndex = i;
for (int j = i + 1; j < array.Length; j++)
{
if (array[minIndex] > array[j])
{
minIndex = j;
}
}
if (minIndex != i)
{
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
--------插入排序
private static void InsertSortNum()
{
int[] unsorted = new int[5] { 5, 2, 4, 6, 1 };
for (int i = 0; i < unsorted.Length; i++)
{
//存储当前unsorted[i]的值
int temp = unsorted[i];
//存储当前值的下标
int j = i;
//判断当前值与其前一位的大小
while (j > 0 && unsorted[j - 1] > temp)
{
//如果前一位值大于当前值,与unsorted[j] = temp 构成交换值的操作
unsorted[j] = unsorted[j - 1];
j--;
}
//这个unsorted[j] 相当于unsorted[j-1]
unsorted[j] = temp;
}
for (int i = 0; i < unsorted.Length; i++)
{
Console.WriteLine(unsorted[i]);
}
}
--------快排
private void QuickSort(int[] arr, int low, int high)
{
if (low < high)
{
int index = CacluateSort(arr, low, high);
QuickSort(arr, low, index - 1);
QuickSort(arr, index + 1, high);
}
}
private int CacluateSort(int[] arr,int low,int high)
{
int basePoivt = arr[low];
while(low<high)
{
while (low < high && arr[high] >= basePoivt)
{
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= basePoivt)
{
low++;
}
arr[high] = arr[low];
}
arr[low] = basePoivt;
return low;
}