插入排序:
直接插入排序:
void InsertSort(ElemType A[], int n)
{
int i, j;
for (int i = 2; i <= n; i++) // 从第二个元素开始遍历数组
if (A[i] < A[i - 1]) // 如果当前元素小于前一个元素
{
A[0] = A[i]; // 将当前元素暂存到A[0]
for (j = i - 1; A[0] < A[j]; j--) // 从后往前遍历已排序部分
A[j + 1] = A[j]; // 将大于当前元素的值向后移动
A[j + 1] = A[0]; // 插入当前元素到正确位置
}
}
折半插入排序:
void InsertSort(ElemType A[], int n)
{
int i, j, low, high, mid;
for (int i = 2; i <= n; i++)
A[0] = A[i];
low = 1;
high = i - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (A[mid] > A[0])
high = mid - 1;
else
low = mid + 1;
}
for (j = i - 1; j >= high + 1; j--)
A[j + 1] = A[j];
A[high + 1] = A[0];
}
希尔排序:
void ShellSort(ElemType A[], int n)
{
int dk, i, j;
for (dk = n / 2; dk >= 1; dk = dk / 2)
for (int i = dk + 1; i <= n; i++)
if (A[i] < A[i - dk])
{
A[0] = A[i];
for (j = i - dk; j > 0 && A[0] < A[j]; j -= dk)
A[j + dk] = A[j];
A[j + dk] = A[0];
}
}
交换排序:
冒泡排序:
void sort(ElemType arr[],int n){
//外层循环
for (int i = 0; i < n-1; ++i) {
int flag=1; //假设flag=1 就是已经排序好的
//内层循环
for (int j = 0; j < n-1-i; ++j) {
//判断升序 赋值
//如果是降序的话 把> 改成<即可
if(arr[j]>arr[j+1]){
int tem=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tem;
//如果进行了元素交换 就说明没有排序好
flag=0;
}
}
if(flag==1){
break;
}
}
}
快速排序:
//划分算法
int Partition(ElemType A[], int low, int high)
{
ElemType pivot = A[low];
while (low < high)
{
while (low < high && A[high] >= pivot)
--high;
A[low] = A[high];
while (low < high && A[low] <= pivot)
++low;
A[high] = A[low];
}
A[low] = pivot;
return low;
}
//对枢轴两个表划分 然后递归调用快速排序算法排序
void QuickSort(ElemType A[],int low,int high){
if(low<high){
int pivot_pos=Partition(A,low,high);
QuickSort(A,low,pivot_pos-1);
QuickSort(A,pivot_pos+1,high);
}
}
选择排序:
简单选择排序:
void SelectSort(ElemType A[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min = i;
for (int j = i + 1; j < n; j++)
if (A[j] < A[min])
min = j;
if (min != i)
swap(A[i], A[min]);
}
}
堆排序(大根堆):
// 建堆
void BuildMaxHeap(ElemType A[], int len)
{
for (int i = len / 2; i > 0; i--)
HeadAdjust(A, i, len);
}
// 调整
void HeadAdjust(ElemType A[], int k, int len)
{
A[0] = A[k];
for (int i = 2 * k; i <= len; i *= 2)
{
if (i < len && A[i] < A[i + 1])
i++;
if (A[0] >= A[i])
break;
else
{
A[k] = A[i];
k = i;
}
}
A[k] = A[0];
}
void HeapSort(ElemType A[], int len)
{
BuildMaxHeap(A, len);
for (int i = len; i > 1; i--)
{
swap(A[i], A[1]);
HeadAdjust(A, 1, i - 1);
}
}
归并排序:
归并排序:
void Merge(ElemType A[], int low, int mid, int high)
{
int i, j, k;
for (k = low; k <= high; k++)
B[k] = A[k];
for (i = low, j = mid + 1, k = i; i <= mid && j <= high; k++)
{
if (B[i] <= B[j])
A[k] = B[i++];
else
A[k] = B[j++];
}
while (i <= mid)
A[k++] = B[i++];
while (i <= high)
A[k++] = B[j++];
}
void MergeSort(ElemType A[], int low, int high)
{
if (low < high)
int mid = (low + high) / 2;
MergeSort(A, low, mid);
MergeSort(A, mid + 1, high);
Merge(A, low, mid, high);
}
标签:high,dk,int,ElemType,void,77,算法,low,排序
From: https://www.cnblogs.com/gaodiyuanjin/p/18620325