插入算法(C语言)

来源:互联网 发布:第二个爸爸知乎 编辑:程序博客网 时间:2024/06/03 17:08

插入排序算法中的直接排序算法,折半插入排序算法,希尔排序算法。

 这三个算法理解顺序:直接----->折半-------->希尔排序算法。


#include<stdio.h>#include<stdlib.h>#define N 10typedef int KeyType;    //定义关键字类型typedef int DataType;    //其他数据类型typedef struct//记录数据结构{KeyType key;//关键字DataType data;//其他数据}RecType;/* InitRec : 创建排序的结构体数组 */void InitRec(RecType arr_Rec[],int a[], int n){int i = 0;for (i = 0; i < n; ++i){arr_Rec[i].key = a[i];   //排序的数据arr_Rec[i].data = 0;}}/* ShowData: 递归方式顺序打印排序结构体数组的关键字 */void ShowData(RecType arr_Rec[], int n){if (n == 0) //到达末尾{printf("\n\n");return;}else{printf(" %-5d", arr_Rec[0].key);RecType *p;p = arr_Rec;p++;ShowData(p, n - 1);}}/*StraightInsertSort: 直接插入排序,将前面的元素设为有序区,后面的元素为无序区。一开始的时候有序区只有一个元素就是 R[0] */void StraightInsertSort(RecType R[],int n){int i, j;KeyType temp;     //定义中间变量,用于临时存储int k=0;for (int i = 1; i < n; i++)  //因为第一个数不需要排序,所以从第二个开始循环{temp = R[i].key;     //存储当前要插入到有序区间的元素j = i - 1;while (j >= 0 && temp < R[j].key)  //将比temp大的数往后移一位,位插入做准备{k++;printf(" %d \n", k);     R[j + 1] = R[j];          j--;}R[j+1].key = temp;     //插入ShowData(R, n);}}/* BinaryInsertSort : 折半插入排序,折半查找算法对直接插入排序优化,将待插入到有序区的元素插入的时候利用折半查找找到插入的位置 */void BinaryInsertSort(RecType R[], int n){int i, j, low, high, mid;RecType temp;  //准备存储中间变量for (i = 1; i < n; i++){temp = R[i];     //将要插入的元素,这和直接插入排序是一样的j = i - 1;        low = 0;high = i - 1;while (low <= high)     //因为有序区已经有序,可以利用折半查找找到插入的位置{mid = (low + high) / 2;   if (temp.key < R[mid].key)      //说明temp(也就是R[i])的key值在R[low]到R[mid-1]之间high = mid - 1;else                    //说明temp(也就是R[i])的key值在R[mid+1]到R[high]之间low = mid + 1;}                             //当low>high时,找到了插入的位置就是high+1了for (j = i - 1; j >= high + 1; j--)R[j + 1] = R[j];R[high+1] = temp;ShowData(R, n);}}/* SellSort: 希尔排序算法 */void ShellSort(RecType R[], int n){int i, j, gap;     //gap为增量RecType temp;       gap = n / 2;//增量初值为总的一半while (gap > 0){for (i = gap; i < n; i++)  //这是关键,其实就是对相隔gap的元素进行直接插入排序{temp = R[i];j = i - gap;while (j >= 0 && temp.key < R[j].key)  //这里明显就是直接插入排序,只是这里不是1而是gap{//当gap=2的时候,就是直接插入排序R[j + gap] = R[j];j = j - gap;}R[j + gap] = temp;}gap = gap / 2;    }}int main(){int a[N] = {4,2,6,9,5,7,1,3,8,10};//int a[N] = {10,9,8,7,6,5,4,3,2,1};//int a[N] = {1,2,3,4,5,6,7,8,9,10 };RecType arr_Rec[N];InitRec(arr_Rec, a, N);//printf("%d\n", arr_Rec[])ShowData(arr_Rec, N);//StraightInsertSort(arr_Rec, N);BinaryInsertSort(arr_Rec, N);ShowData(arr_Rec, N);system("pause");return 0;}


0 0