#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct{
int r[MAXSIZE + 1]; //用于存储要排序的数组,r[0]用作哨兵或临时变量
int length; //用于记录顺序表的长度
}SqList;
typedef enum{
FALSE = 0,
TRUE
}Status;
//打印排序结果
void Print_Result(SqList *L){
printf("排序结果:\n");
for (int i = 1; i <= L->length; i++){
printf("%d ", L->r[i]);
}
printf("\n");
}
//直接插入排序
void InsertSort(void)
{
int i, j;
SqList L = { { 0, 26, 5, 37, 1, 61, 11, 59, 15, 48, 19}, MAXSIZE };//首元素作哨兵,不参与排序运算
int a=1;
do{
printf("直接插入排序过程:\n");
for (i = 2; i <= L.length; i++){
a++;
if (L.r[i] < L.r[i - 1]){
L.r[0] = L.r[i];//哨兵元素,即此处记录为待操作元素
for (j = i - 1; L.r[j] > L.r[0]; j--){
L.r[j + 1] = L.r[j];//元素往后移动,腾出位置
}
L.r[j + 1] = L.r[0];//找到了合适位置,插入哨兵元素
}
printf("第%d躺的",a-1);
Print_Result(&L);
}
}while(a<L.length);
printf("最终直接插入排序的");
Print_Result(&L);//打印排序结果
}
//希尔排序
void ShellSort(void){
int i, j;
SqList L = { { 0, 26, 5, 37, 1, 61, 11, 59, 15, 48,19 }, MAXSIZE };//首元素作哨兵,不参与排序运算
int increment = L.length;
do{
increment = increment / 2; //此处自定义增量序列
for (i = increment+1; i <= L.length; i++){
if (L.r[i] <= L.r[i - increment]){
L.r[0] = L.r[i];
for (j = i - increment; j > 0 && L.r[j] > L.r[0]; j -= increment){
L.r[j + increment] = L.r[j];
}
L.r[j + increment] = L.r[0];
}//此处实质为直接插入排序,只不过增量变为increment,而不是1
}
printf("对增量为 %d 的序列进行希尔排序", increment);
Print_Result(&L);//打印希尔排序中间过程结果
} while (increment > 1);//根据增量序列,进行多次直接插入排序
printf("最终希尔排序的");
Print_Result(&L);//打印最终排序结果
}
//交换数组前后两个元素
void Swap(SqList *L, int i, int j){
int temp = L->r[i];
L->r[i] = L->r[j];
L->r[j] = temp;
}
//快速排序
int Partition(SqList *L, int low, int high){
int pivotkey;
pivotkey = L->r[low];//固定选取第1个元素为枢轴
while (low < high){
while (low < high && L->r[high] >= pivotkey){
high--;
}
Swap(L, low, high);
while (low < high && L->r[low] <= pivotkey){
low++;
}
Swap(L, low, high);
}
}
//递归调用左右还未排序的进行排序
void QSort(SqList *L, int low, int high){
int pivot;
if (low < high){
pivot = Partition(L, low, high);
QSort(L, low, pivot - 1);
QSort(L, pivot + 1, high);
}
}
//快速排序
void QuickSort(){
SqList L = { { 0, 26, 5, 37, 1, 61, 11, 59, 15, 48, 19}, MAXSIZE };//首元素保留,不参与排序
QSort(&L, 1, L.length);
printf("快速排序的");
Print_Result(&L);//打印最终排序结果
}
void main(){
//直接插入排序
InsertSort();
//希尔排序
ShellSort();
//快速排序
QuickSort();
}