【数据结构】数组操作(LowArrayApp.java)

复制代码
 1 // LowArrayApp.java  
 2 // demonstrates array class with low-level interface
 3 // to run this program: C>java LowArrayAPP
 4 //java数据结构和算法(第二版)拉佛 著  pdf第46页  数组操作
 5 
 6 package first;
 7 
 8 class LowArray
 9 {
10     private long[] a;                 // ref to array a
11     
12     public LowArray(int size)         // constructor
13     { a = new long[size]; }           // create array
14     
15     public void setElem(int index, long value)      // set value
16     { a[index] =  value; }
17     
18     public long getElem(int index)    // get value
19     { return a[index]; }
20     
21 }    // end class LowArray
22 
23 
24 public class LowArrayAPP 
25 {
26     public static void main(String[] args)
27     {
28         LowArray arr;                  // reference
29         arr = new LowArray(100);       //create LowArray object
30         int nElems = 0;                // number of items in array
31         int j;                         // loop variable
32         
33         arr.setElem(0, 77);
34         arr.setElem(1, 99);
35         arr.setElem(2, 44);
36         arr.setElem(3, 55);
37         arr.setElem(4, 22);
38         arr.setElem(5, 88);
39         arr.setElem(6, 11);
40         arr.setElem(7, 00);
41         arr.setElem(8, 66);
42         arr.setElem(9, 33);
43         nElems = 10;        // now 10 items in array
44     
45     // display items
46     for (j = 0; j < nElems; j++) 
47         System.out.print(arr.getElem(j) + " ");
48         System.out.println("");
49     
50     //search for data item
51     int searchKey = 26;
52     for(j=0; j < nElems; j++)
53         if(arr.getElem(j) == searchKey)
54             break;
55     if(j == nElems)
56         System.out.println("Can't find " + searchKey);
57     else
58         System.out.println("Found " + searchKey);
59     
60     //delete value 55
61     for(j = 0; j < nElems; j++)
62         if (arr.getElem(j) == 55)
63             break;
64     
65     for(int k = j; k < nElems; k++)        // 删掉的数据项后面所有单元逐个前移一位
66         arr.setElem(k, arr.getElem(k+1));
67     nElems--;
68     
69     // display items
70         for (j = 0; j < nElems; j++) 
71             System.out.print(arr.getElem(j) + " ");
72             System.out.println("");
73     
74     } // end main()
75 } // end class LowArrayAPP 


运行结果:
77 99 44 55 22 88 11 0 66 33 
Can't find 26
77 99 44 22 88 11 0 66 33 

 

 
复制代码

 

posted @   Thermo  阅读(363)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示