## 問題描述
> 線性表(a1,a2,a3,...,an)中元素遞增有序,且按順序存儲于計算機內。要求設計一算法完成用最少時間在表中查找數據值為x的元素;若找到,將其與后繼元素位置交換;若找不到將其插入到表中,使表中的元素仍遞增有序
## 算法思想
> 本題遞增有序,為了在最少的事件內完成指定數據x的查找,那么我們可以采用折半查找的思想查找x,如果找到,那么與后繼元素交換一次,如果找不到則順序插入便可。
## 算法描述
~~~
int FindDI(SqList *L, ElemType x)
{
int low=0, high=L->length-1;
int mid;
//折半查找
while(low<high){
mid=(low+high)/2;
if(L->data[mid]==x){
break;
}else if(L->data[mid]<x){
low=mid+1;
}else{
high=mid-1;
}
}
//已找到,與后繼元素位置交換
if(L->data[mid]==x&&L->data[mid]!=L->length-1){
ElemType temp;
temp=L->data[mid];
L->data[mid]=L->data[mid+1];
L->data[mid+1]=temp;
return mid+1;
}
//未找到,插入該元素,并且使表中的元素仍遞增有序
if(low>high){
int i;
for(i=L->length;i>mid;i--){
L->data[i]=L->data[i-1];
}
L->data[i]=x;
L->length=L->length+1;
return -1;
}
return 0;
}
~~~
具體代碼見附件
## 附件
~~~
#include<stdio.h>
#define MaxSize 100
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int length;
}SqList;
int FindDI(SqList*, ElemType);
void Print(SqList*);
int main(int argc,char *argv[])
{
SqList SL;
ElemType e=4;
SL.length=10;
for(int i=0;i<SL.length;i++){
SL.data[i]=2*i+1;
}
Print(&SL);
int flag=FindDI(&SL,e);
if(flag==-1){
printf("Find fail!,It will be instered the true position\n");
Print(&SL);
}else{
printf("Find success!\n");
printf("It is posed %dth, It will swap with next number!\n", flag);
Print(&SL);
}
return 0;
}
int FindDI(SqList *L, ElemType x)
{
int low=0, high=L->length-1;
int mid;
while(low<high){
mid=(low+high)/2;
if(L->data[mid]==x){
break;
}else if(L->data[mid]<x){
low=mid+1;
}else{
high=mid-1;
}
}
if(L->data[mid]==x&&L->data[mid]!=L->length-1){
ElemType temp;
temp=L->data[mid];
L->data[mid]=L->data[mid+1];
L->data[mid+1]=temp;
return mid+1;
}
if(low>high){
int i;
for(i=L->length;i>mid;i--){
L->data[i]=L->data[i-1];
}
L->data[i]=x;
L->length=L->length+1;
return -1;
}
return 0;
}
void Print(SqList *L)
{
for(int i=0;i<L->length;i++){
printf("%4d",L->data[i]);
}
printf("\n");
}
~~~
- 前言
- 緒論
- 第1章線性表
- 第1章第1節 線性表的順序表示
- 第1章第1節練習題1 刪除最小值
- 第1章第1節練習題2 逆置順序表
- 第1章第1節練習題3 刪除指定元素
- 第1章第1節練習題4 有序表刪除指定區間值
- 第1章第1節練習題5 無序表刪除指定區間值
- 第1章第1節練習題6 刪除重復值
- 第1章第1節練習題7 順序表的歸并
- 第1章第1節練習題8 順序表循環移位
- 第1章第1節練習題9 查找指定值
- 第1章第1節練習題10 查找中位數
- 第1章第2節 線性表的鏈式表示(1)
- 第1章第2節 線性表的鏈式表示(2)
- 第1章第2節 線性表的鏈式表示(3)
- 第1章第2節練習題1 遞歸刪除指定結點
- 第1章第2節練習題2 非遞歸刪除指定結點
- 第1章第2節練習題3 刪除最小值結點
- 第1章第2節練習題4 刪除指定區間結點
- 第1章第2節練習題5 刪除重復結點
- 第1章第2節練習題6 反向輸出
- 第1章第2節練習題7 遞減輸出
- 第1章第2節練習題8 奇偶拆分單鏈表
- 第1章第2節練習題9 查找公共結點
- 第1章第2節練習題10 查找指定倒數結點
- 第1章第2節練習題11 就地逆置單鏈表
- 第1章第2節練習題12 單鏈表之插入排序
- 第1章第2節練習題13 單鏈表之選擇排序
- 第1章第2節練習題14 判斷子序列
- 第1章第2節練習題15 拆分并逆序單鏈表
- 第1章第2節練習題16 歸并并逆序單鏈表
- 第1章第2節練習題17 使用相同值結形成新單鏈表
- 第1章第2節練習題18 求兩個單鏈表的交集
- 第1章第2節練習題19 判斷循環雙鏈表對稱
- 第1章第2節練習題20 連接兩個循環單鏈表
- 第1章第2節練習題21 輸出并刪除最小值結點
- 第1章第2節練習題22 按結點訪問頻度排序
- 第1章第3節 線性表的比較
- 第2章受限的線性表
- 第2章第1節 棧
- 第2章第1節練習題1 判斷棧的操作次序是否合法
- 第2章第1節練習題2 判斷是否中心對稱
- 第2章第2節 隊列
- 第2章第1節練習題3 共享棧的基本操作
- 第2章第2節練習題1 逆置隊列
- 第2章第2節練習題2 使用棧模擬隊列操作
- 第2章第2節練習題3 使用隊列模擬渡口管理
- 第2章第3節 串
- 第2章第3節練習題1 串的模式匹配(Basic)
- 第2章第3節練習題2 串的模式匹配(KMP)