将一个数插入有序数组中,保持数组的有序性不变
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode *List;
struct LNode{
int data[100];
int Last;
};
int BinarySearch(List L, int X){
int Left,Right,Mid;
Left = 0;
Right = L->Last;
while(Left<=Right){
Mid = (Right+Left)/2;
if(X<L->data[Mid])
Right = Mid-1;
else if(X>L->data[Mid])
Left = Mid+1;
else
return Mid;
}
return Left;
}
int main(void){
List L = (List)malloc(sizeof(struct LNode));
int i,X,N,index;
scanf("%d %d",&N,&X);
L->Last = -1;
for(i=0;i<N;i++){
scanf("%d",&L->data[i]);
L->Last++;
}
index = BinarySearch(L,X);
for(i=N-1;i>=index;i--){
L->data[i+1] = L->data[i];
}
L->data[index] = X;
L->Last++;
for(i=0;i<=L->Last;i++)
printf("%d ",L->data[i]);
return 0;
}
版权声明:本文为AlenSmithing原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。