线性表(a1,a2,a3,...,an)中元素递增有序且按顺序存储于计算机内,要求设计一算法完成:
1)用最少时间在表中查找元素数值为x的元素
2)若找到将其与后继元素位置相交换
3)若找不到将其插入表中并使表中元素仍然递增有序
#include <stdio.h> #define N 8 #define ElemType int int SearchExchangeInsert(ElemType a[],ElemType x) { int low,high,mid,i; low = 0,high = N-2; while(low <= high) { mid = (low + high)/2; if(a[mid] == x) break; else if(a[mid] < x){ low = mid + 1; } else{ high = mid -1; } } if(a[mid] == x && mid != N-2)//若最后一个元素与x相等,则不存在与其后继交换的操作 { a[mid] = a[mid+1] - a[mid] + (a[mid+1] = a[mid]); } if(low > high)//查找失败,插入元素x { for(i=N-2;i>high;i--)//a[high] < x,high之后都比x大 a[i+1] = a[i]; a[i+1] = x; return 1; } return 0; } int main() { ElemType a[N] = {1,4,7,10,20,23,25};//默认最后一个数为0 ElemType x = 26;//0,1,3,8,25,26 if(SearchExchangeInsert(a,x))//x插入表中 for(int i=0;i<N;i++) printf("%d,",a[i]); else{ for(int i=0;i<N-1;i++) printf("%d,",a[i]); } return 0; }
时间: 2024-10-10 18:12:43