栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

SWUST 软件实验之折半查找

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SWUST 软件实验之折半查找

#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);//折半查找
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001187.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号