#include<iostream>
using namespace std;
const int maxsize = 1000;
//插入排序++
void InsertSort(int A[], int n)
{
int i, j;
for (i = 2; i < n; i++)
{
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 BubbleSort(int A[], int n)
{
int i, j, flag, temp;
for (i = 0; i <n - 1; i++)
{
flag = 0;
for (j = n - 1; j > i; j--)
{
if (A[j - 1] > A[j])
{
swap(A[j - 1], A[j]);
flag = 1;
}
}
if (!flag) return; //如果本趟没有发生交换,即可退出排序!
}
}
//快速排序
void QuickSort(int A[], int l, int r)
{
if (l >= r) return;
int i = l - 1, j = r + 1;
int x = A[(i + j) / 2];
while (i < j)
{
do i++; while (A[i] < x);
do j--; while (A[j] > x);
if (i < j) swap(A[i], A[j]);
}
QuickSort(A, l, j);
QuickSort(A, j + 1, r);
}
//选择排序
void SelectSort(int A[], int n)
{
int i, j, k, temp;
for (i = 0; i < n; i++)
{
k = i;
for (j = i + 1; j < n; j++)
if (A[k] > A[j])
k = j;
swap(A[i], A[k]);
}
}
//归并排序
void merge(int A[], int l1, int r1, int l2, int r2)
{
int q[maxsize], i, j, index = 0;
i = l1, j = l2;
while (i <= r1 && j <= r2)
{
if (A[i] < A[j]) q[index++] = A[i++];
else q[index++] = A[j++];
}
//左右序列剩余的放入q数组
while (i <= r1) q[index++] = A[i++];
while (j <= r2) q[index++] = A[j++];
//将q临时存储的数值放回A数组中
for (int k = 0; k < index; k++)
A[l1 + k] = q[k];
}
void mergesort(int A[], int left, int right)
{
int mid = (left + right) / 2;
if (left < right)
{
mergesort(A, left, mid);
mergesort(A, mid + 1, right);
merge(A, left, mid, mid + 1, right);//把左右两边合并
}
}
//堆排序
void HeadAdjust(int A[], int k, int n) //将元素K为根的子树进行调整
{
A[0] = A[k];
for (int i = 2 * k; i <= n; i *= 2)
{
if (i < n && 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(int A[], int n)
{
//建立初始堆
for (int i = n / 2; i > 0; i--)
HeadAdjust(A, i, n);
//堆排序
for (int i = n; i > 1; i--)
{
swap(A[i], A[1]);
HeadAdjust(A, 1, i - 1);
}
}
//折半插入排序
void BinInsertSort(int A[], int n)
{
int i, j, low, high, mid;
for (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(int A[], int n)
{
int d; //步长
int i, j;
for (d = n / 2; d >= 1; d /= 2) //步长变化
{
for (i = d + 1; i <= n; i++)
{
if (A[i] < A[i - d])
{
A[0] = A[i]; //A[0]只是暂存单元,不是哨兵
for (j = i - d; j > 0 && A[0] < A[j]; j -= d)
A[j + d] = A[j];
A[j + d] = A[0];
}
}
}
}
int main()
{
int A[11] = { 0,5,2,9,5,7,6,9,34,20,1 };
//mergesort(A, 0, 11 - 1);
//HeapSort(A, 11 - 1);
//BinInsertSort(A, 11 - 1);
//ShellSort(A, 11 - 1);
for (int i = 0; i < 11; i++) cout << A[i] << " ";
}
数据结构中排序算法的实现
于 2022-10-21 22:02:19 首次发布