數組_算法1

`package com.ithelei.cn;

 public class LowArray {

private long[] a;// 存儲數據的數組,容器

// 構造函數
public LowArray(int size) {// 參數代表數組的大小,里面能存多少個元素
    a = new long[size];
}
//添加數據方法
public void setElem(int index, long value) {//下標索引,傳過來的數據
   //操作數組
    a[index]=value;
}

public  long getElem(int index){

    return a[index];
    
}
}
`

 `
   package com.ithelei.cn;
   public class ArrayApp {
   public static void main(String[] args) {

    LowArray arr;
    arr = new LowArray(100);
    int nElems;// 元素個數
    int j;// 循環
    long searchKey;// 查找的數據項

    arr.setElem(0, 77);// 第一個參數是位置
    arr.setElem(1, 99);
    arr.setElem(2, 44);
    arr.setElem(3, 55);
    arr.setElem(4, 22);
    arr.setElem(5, 88);
    arr.setElem(6, 11);
    arr.setElem(7, 00);
    arr.setElem(8, 66);
    arr.setElem(9, 33);

    nElems = 10;
    // 顯示所有元素-------------
    for (j = 0; j < nElems; j++)
    System.out.print(arr.getElem(j) + " ");
    System.out.println();

    // 查找26
    searchKey = 26;
    for (j = 0; j < nElems; j++)
    if (arr.getElem(j) == searchKey)break;
        
    if (j == nElems)
        System.out.println("沒有找到" + searchKey);
    else
        System.out.println("找到了" + searchKey);

    // 刪除55
    searchKey = 55;
    for (j = 0; j < nElems; j++)
    if (arr.getElem(j) == searchKey)break;

    for (int k = j; k < nElems; k++)
    arr.setElem(k, arr.getElem(k + 1));
    nElems--;

    // 顯示所有元素
    for (j = 0; j < nElems; j++)
    System.out.print(arr.getElem(j) + " ");
    System.out.println();
}

}
`
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容