#include
#include
#define MAX_SIZE 10
typedef struct
{
int arr[MAX_SIZE + 1]; //数据集合(1个哨兵 + 10个数据)
int length;
}SearchDataStruct;
void printResult(int res)
{
printf("索引为: %dn", res);
}
void Print_Result(SearchDataStruct *L){
printf("直接插入排序结果:n");
for (int i = 1; i <= L->length; i++){
printf("%d ", L->arr[i]);
}
printf("n");
}
void InsertSort(SearchDataStruct *L){
int i, j;
for (i = 2; i <= L->length; i++){
if (L->arr[i] < L->arr[i - 1]){
L->arr[0] = L->arr[i];//哨兵元素,即此处记录为待操作元素
for (j = i - 1; L->arr[j] > L->arr[0]; j--){
L->arr[j + 1] = L->arr[j];//元素往后移动,腾出位置
}
L->arr[j + 1] = L->arr[0];//找到了合适位置,插入哨兵元素
}
}
Print_Result(L);
}
//折半查找
int Binary_Search(SearchDataStruct *L)
{
int low, high, mid, result = -1;
int keyValue = 37;//待查找元素
SearchDataStruct search =*L;
low = 1;
high = search.length;
while (low <= high){
mid = (low + high) / 2;
if (keyValue < search.arr[mid]){//左
high = mid - 1;
}
else if (keyValue > search.arr[mid]){//右
low = mid + 1;
}
else{ //找到待查找元素
result = mid;
break;
}
}
printResult(result);
}
void main(){
SearchDataStruct L= { { 0, 26, 5, 37, 1, 61, 11, 59, 15, 48, 19},MAX_SIZE };
InsertSort(&L);
Binary_Search(&L);//折半查找
}



