#region 快速排序
public static void quickSort(int[] array)
{
sort(array, 0, array.Length - 1);
}
/// <summary>
/// 排序
/// </summary>
/// <param name="array">需要排列的数组</param>
/// <param name="low">低位</param>
/// <param name="high">高位</param>
static void sort(int[] array, int low, int high)
{
if (low >= high)
{
return;
}
// 基准值 选取当前数组第一个值
int index = array[low];
// 低位i从左向右扫描
int i = low;
// 高位j从右向左扫描
int j = high;
while (i < j)
{
while (i < j && array[j] >= index)
{
j--;
}
if (i < j)
{
array[i] = array[j];
i++;
}
while (i < j && array[i] < index)
{
i++;
}
if (i < j)
{
array[j] = array[i];
j--;
}
}
array[i] = index;
// 左边的继续递归排序
sort(array, low, i - 1);
// 右边的继续递归排序
sort(array, i + 1, high);
}
#endregion
#region 堆排序
static void HeapSort(int[] tree)
{
BuildHeap(tree, tree.Length); // 构造堆
for (int i = tree.Length - 1; i >= 0; i--)
{
Swap(tree, i, 0); // 交换根节点跟最后一个节点
Heapify(tree, i, 0); // 去掉最后一个值
}
}
static void BuildHeap(int[] tree, int length)
{
int lastIndex = length - 1; // 获取最后一个节点下标
int parentIndex = (lastIndex - 1) / 2; // 获取父节点下标
// 对这些节点heapify
for (int i = parentIndex; i >= 0; i--)
{
Heapify(tree, length, i);
}
}
static void Heapify(int[] tree, int length, int heapIndex)
{
if (heapIndex >= length)
return;
int leftChildIndex = 2 * heapIndex + 1; // 计算左子节点的下标
int rightChildIndex = 2 * heapIndex + 2; // 计算右子节点下标
int maxIndex = heapIndex; // 最大节点的下标
// 比较最大节点的下标
if (leftChildIndex < length && tree[leftChildIndex] > tree[maxIndex])
maxIndex = leftChildIndex;
if (rightChildIndex < length && tree[rightChildIndex] > tree[maxIndex])
maxIndex = rightChildIndex;
// 如果最大节点不是父节点才处理
if (maxIndex != heapIndex)
{
// 交换值
Swap(tree, maxIndex, heapIndex);
// 对处理的节点再次进行Heapify
Heapify(tree, length, maxIndex);
}
}
/// <summary>
/// 交换位置
/// </summary>
/// <param name="left">前一个数</param>
/// <param name="right">后一个数</param>
static void Swap(int[] L, int i, int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
#endregion