数组简单操作

package com.datastructure.array;


public class Example1 {
  private long[] arr;
  //有效数据的多少 长度
  private int elements;//初始化为0
  
  public Example1(){
 arr = new long[50];
  }
  public Example1(int maxsize){
 arr = new long[maxsize];
  }
  /**
   * 无序添加数据
   */
  public void insert(long value){
 arr[elements] = value;
 elements++;
  }
  /**
   * 有序添加数据
   */
  public void insertorder(long value){
 int i;
 for(i = 0;i<elements;i++){
 if(arr[i]>value){
 break;
 }
 }
 for(int j=elements;j>i;j--){
 arr[j] = arr[j-1];
 }
 arr[i] = value;
 elements++;
  }
  /**
   * 显示数据
   */
  public void display(){
 System.out.print("[");
 for(int i=0;i<elements;i++){ 
 if(i == (elements-1)){
 System.out.print(arr[i]);
 }else{
 System.out.print(arr[i]+",");
 }
 }
 System.out.print("]");
  }
  /** 
   * 属于线性查找
   * 根据值查找数据返回索引
   */
  public int search(long value){
 int i;
 for(i=0;i<elements;i++){
 if(value == arr[i]){
 break;
 }
 }
 if(i == elements){
 return -1;
 }else{
 return i;
 }
  }
  /**
   * 二分法查找 前提,需要数组是有序,从中间分割
   * 根据值查找数据返回索引
   * -------------------------------------------------------------------
   * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
   * -------------------------------------------------------------------
   */
  public int getindex(long value){
 int middle = 0;//中间值
 int low = 0;//起始位置
 int pow = elements;//最后位置
 while(true){
 middle = (pow + low) / 2;
 if(arr[middle] == value){
 return middle;
 }else if(low > pow){
 return -1;
 }else{
 if(arr[middle] > value){
 pow = middle - 1;
 }else{
 low = middle + 1;
 }
 }
 }
  }
  /** 
   * 根据索引查找 
   */
  public long get(int index){
 if(index>=elements || index<0){
 throw new ArrayIndexOutOfBoundsException();
 }else{
return arr[index];
 }
  }
  /**
   * 删除数据
   */
  public void delete(int index){
 if(index>=elements || index<0){
 throw new ArrayIndexOutOfBoundsException();
 }else{
 for(int i=index;i<elements;i++){
 arr[i] = arr[i+1];
 }
 elements--;
 }
  }
  /**
   * 更新数据
   * @param index 索引
   * @param value 更新后的值
   */
  public void update(int index,long value){
 if(index>=elements || index<0){
 throw new ArrayIndexOutOfBoundsException();
 }else{
 arr[index] = value;
 }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章