版权声明:本文为King_HAW原创文章,未经King_HAW允许不得转载。 https://blog.csdn.net/King_HAW/article/details/74335370
版权申明:
本实验的实验目的,实验内容,实验要求归东北大学所有,未经许可禁止转载。
实验七 查找
实验目的:
掌握折半查找算法;理解其时间复杂度与顺序查找的不同。
实验内容:
1. 构建一个顺序存储的数表(或数组),声明low, high和middle变量;
2. 0号单元不用,当操作返回0时,意味着该数不存在数表(或数组)中;
3. 在low<=high时,比较middle位置的值和查找的关键字,不断缩小查找区间;
4. 当low>high时,意味查找不成功。
源码:
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MAXSIZE 100
/***********类型定义***********/
typedef struct{
int r[MAXSIZE + 1];
int length;
}SqList;
/***********初始化***********/
int InitList(SqList *L){
//SqList *L;
L = (SqList*)malloc(sizeof(SqList));
if(!L)
exit(OVERFLOW);
L->length = 0;
return OK;
}
/***********创建表***********/
int CreateList(SqList *L, int n){
int e, i;
printf("请输入元素:\n");
for(i = 1; i <= n; i++){
scanf("%d", &e);
L->r[i] = e;
}
L->length = n;
return OK;
}
/***********打印表***********/
int PrintList(SqList *L){
int i;
for(i = 1; i <= L->length; i++){
printf("%2d", L->r[i]);
}
return OK;
}
int LT(int i, int j){
if(i >= j)
return 0;
else
return 1;
}
/***********插入排序***********/
void InsertSort(SqList *L){
int i, j;
for(i = 2; i <= L->length; i++){
if(LT(L->r[i], L->r[i-1])){
L->r[0] = L->r[i];
L->r[i] = L->r[i-1];
for(j = i - 2; LT(L->r[0], L->r[j]); --j){
L->r[j+1] = L->r[j];
}
L->r[j+1] = L->r[0];
}
}
}
int main()
{
SqList L;
int n;
InitList(&L);
printf("请输入元素个数:\n");
scanf("%d", &n);
CreateList(&L, n);
printf("数组为:\n");
PrintList(&L);
printf("\n\n******插入排序******\n");
InsertSort(&L);
printf("\n排序后的数组为:\n");
PrintList(&L);
printf("\n");
return 0;
}
运行结果: