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; } } }
时间: 2025-01-01 23:26:05