数组-2分查找2

package a_array.C;


/**
 * twoPointSearch
 * 
 * @author Administrator
 *
 */
public class OrderApp {
public static void main(String[] args) {
TwoPointsSearch theArr = new TwoPointsSearch(20);
theArr.insert(10);
theArr.insert(30);
theArr.insert(22);
theArr.insert(75);
theArr.insert(34);
theArr.insert(57);
theArr.insert(89);
theArr.insert(49);
theArr.insert(31);
theArr.insert(1);


int searchKey = theArr.find(49);
if (searchKey == theArr.size()) {
System.out.println("没锟揭碉拷");
} else
System.out.println("锟揭碉拷" + searchKey);


theArr.display();
theArr.delete(89);
theArr.display();


}
}package a_array.C;


public class TwoPointsSearch {
private int nElems;
private int[] arr;


public TwoPointsSearch(int max) {
super();
arr = new int[max];
nElems = 0;
}


/**
* 锟斤拷锟斤拷锟斤拷锟�

* @param key
*/
public void insert(int key) {


int i;
// 锟斤拷锟斤拷锟斤拷确锟斤拷锟斤拷
for (i = 0; i < nElems; i++) {
if (key < arr[i])// ?
break;
}
// 锟狡讹拷位锟斤拷
for (int k = nElems; k > i; k--) {
arr[k] = arr[k - 1];
}
// 锟斤拷值
arr[i] = key;
nElems++;
}


public boolean delete(int key) {
// 锟斤拷锟斤拷锟斤拷确锟斤拷锟斤拷
int i = find(key);
boolean flag = true;
if (i != nElems) {
for (; i < nElems; i++) {
if (key == arr[i]) {
arr[i] = arr[i + 1];
}
}
nElems--;
} else
flag = true;


return flag;
}


/**
* 锟斤拷锟街诧拷锟斤拷

* @param searchKey
*/
public int find(int searchKey) {
int lowerBound = 0;
int upperBound = nElems - 1;
int mid;
int result = nElems;
while (true) {
mid = (lowerBound + upperBound) / 2;
if (arr[mid] == searchKey) { // ?
result = mid;
break;
}
if (lowerBound > upperBound) {
break;
} else {
if (arr[mid] > searchKey) {
upperBound = mid - 1;// ?
} else
lowerBound = mid + 1;// ?
}


}
return result;


}


public void display() {


for (int i = 0; i < nElems; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}


public int size() {
return nElems;
}


/**
* 删锟斤拷锟截革拷锟斤拷锟斤拷
* 锟截革拷锟截硷拷锟斤拷全锟斤拷锟睫革拷为-1锟斤拷然锟斤拷锟狡讹拷锟斤拷锟斤拷锟芥,锟节硷拷小锟斤拷锟斤拷锟叫�

*/
public void noDup() {
// 锟截革拷锟侥关硷拷锟斤拷全锟斤拷锟斤拷锟�-1
for (int i = 0; i < nElems; i++) {
for (int j = 0; j < nElems; j++) {


if (j == i)
continue;
if (arr[i] == arr[j]) {
arr[j] = -1;


}
}
}
// 全锟斤拷-1锟狡讹拷锟斤拷锟斤拷锟斤拷
for (int i = 0; i < nElems; i++) {
if (arr[i] == -1) {
for (int k = i; k < nElems; k++) {
if (arr[k] != -1) {
arr[i] = arr[k];
arr[k] = -1;
break;
}
}
}
}
int count = 0;
// 统锟斤拷-1锟侥革拷锟斤拷然锟斤拷锟饺�
for (int i = 0; i < nElems; i++) {
if (arr[i] == -1)
count++;
}
nElems -= count;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值