数据结构习题-王道书2.9
作者:
nxdxml
,
2021-01-03 11:18:36
,
所有人可见
,
阅读 655
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 +5;
int a[N], n;
// 最短时间递增线性表查找一个数,找到于其后继交换,找不到则插入,王道书(2.9)
void SearchExchangeSort(int a[], int x){
int l = 0, r = n - 1, mid, i;
while(l <= r){
mid = l + r >> 1;
if(a[mid] == x) break;
else if(a[mid] < x) l = mid + 1;
else r = mid - 1;
}
if(a[mid] == x && mid != n - 1) // 找到了且不为最后一个元素
swap(a[mid], a[mid + 1]);
if(l > r){
for(i = n - 1; i > r; i -- ) a[i + 1] = a[i];
a[i + 1] = x;
n ++ ;
}
}
int main(){
int x;
cin >> n >> x;
for(int i = 0; i < n; i ++ ) cin >> a[i];
SearchExchangeSort(a, x);
for(int i = 0; i < n; i ++ ) cout << a[i] << " ";
return 0;
}
/*
5 4
1 2 5 6 7
5 4
1 2 4 6 7
*/