首页 > 代码库 > 封装自定义数组类(java版)
封装自定义数组类(java版)
package com.huowolf.test; public class MyOrderedArray { private long[] arr; //数组中有效元素的多少 private int elems; public MyOrderedArray() { arr = new long[50]; } public MyOrderedArray(int length) { arr = new long[length]; } //插入数据 public void insert(long value) { int i; for ( i = 0; i < elems; i++) { if(arr[i]>value) break; } for(int j = elems; j > i; j--) { arr[j] = arr[j-1]; } arr[i] = value; elems++; } //显示数据 public void display() { for (int i = 0; i < elems; i++) { System.out.print(arr[i]+" "); } System.out.println(); } //查找数据 (线性查找) public int find(long searchValue) { int i; for ( i = 0; i < elems; i++) { if(arr[i] == searchValue) break; } if(i == elems) return -1; else return i; } //二分查找 public int binaryFind(long searchValue) { int left,right,mid; left = 0; right = elems; while(left <= right) { mid = (left+right) /2; if(arr[mid] > searchValue) { right = mid -1; //调整右边界 }else if(arr[mid] < searchValue) { left = mid+1; //调整左边界 } else return mid; } return -1; } //删除数据 public void delete(long deleteValue){ if(find(deleteValue) == -1) { System.out.println("查找不到指定数据,删除失败"); }else { for (int i = find(deleteValue); i < elems; i++) { arr[i] = arr[i+1]; } elems--; } } //修改数据 public void change(long oldValue,long newValue) { if(find(oldValue) == -1) { System.out.println("查找不到指定数据,修改失败"); }else { arr[find(oldValue)] = newValue; } } }
封装自定义数组类(java版)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。