前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构之数组封装

数据结构之数组封装

作者头像
企鹅号小编
发布2018-01-22 14:20:36
5980
发布2018-01-22 14:20:36
举报
文章被收录于专栏:编程

一般数组封装:

packagech01;

publicclassMyArray {

privatelong[]arr;

//表示有效数据的长度

privateintelements;

publicMyArray() {

arr=newlong[50];

}

publicMyArray(intmaxsize) {

arr=newlong[maxsize];

}

/**

* 添加数据

*/

publicvoidinsert(longvalue) {

arr[elements] = value;

elements++;

}

/**

* 显示数据

*/

publicvoiddisplay() {

for(inti = 0; i

}

}

/**

* 查找数据

*/

publicintsearch(longvalue) {

inti;

for(i = 0; i

if(value ==arr[i]) {

break;

}

}

if(i ==elements) {

return-1;

}else{

returni;

}

}

/**

* 查找数据,根据索引来查

*/

publiclongget(intindex) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

returnarr[index];

}

}

/**

* 删除数据

*/

publicvoiddelete(intindex) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

for(inti = index; i

arr[index] =arr[index + 1];

}

elements--;

}

}

/**

* 更新数据

*/

publicvoidchange(intindex,intnewvalue) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

arr[index] = newvalue;

}

}

}

有序数组封装:

packagech01;

publicclassMyOrderArray {

privatelong[]arr;

//表示有效数据的长度

privateintelements;

publicMyOrderArray() {

arr=newlong[50];

}

publicMyOrderArray(intmaxsize) {

arr=newlong[maxsize];

}

/**

* 添加数据

*/

publicvoidinsert(longvalue) {

inti;

for(i = 0; i

if(arr[i] > value) {

break;

}

}

for(intj =elements; j > i; j--) {

arr[j] =arr[j - 1];

}

arr[i] = value;

elements++;

}

/**

* 显示数据

*/

publicvoiddisplay() {

for(inti = 0; i

}

}

/**

* 查找数据(线性数组)

*/

publicintsearch(longvalue) {

inti;

for(i = 0; i

if(value ==arr[i]) {

break;

}

}

if(i ==elements) {

return-1;

}else{

returni;

}

}

/**

* 二分法查找数据(这个数组必须是有序的)

*/

publicintbinarySearch(longvalue) {

intmiddle = 0;

intlow = 0;

intpow =elements;

while(true) {

middle = (pow + low) / 2;

if(arr[middle] == value) {

returnmiddle;

}elseif(low > pow) {

return-1;

}else{

if(arr[middle] > value) {

//往左边继续查

pow = middle - 1;

}else{

//往右边继续查

low = middle + 1;

}

}

}

}

/**

* 查找数据,根据索引来查

*/

publiclongget(intindex) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

returnarr[index];

}

}

/**

* 删除数据

*/

publicvoiddelete(intindex) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

for(inti = index; i

arr[index] =arr[index + 1];

}

elements--;

}

}

/**

* 更新数据

*/

publicvoidchange(intindex,intnewvalue) {

if(index >=elementsindex < 0) {

thrownewArrayIndexOutOfBoundsException();

}else{

arr[index] = newvalue;

}

}

}

本文来自企鹅号 - 全球大搜罗媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文来自企鹅号 - 全球大搜罗媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档