资源描述:
《数据结构 叶核亚(例题)-例题-例题-第7章》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、【例7.1】顺序表的顺序查找算法实现与测试。importds_java.LinearList1;//线性表的顺序存储结构publicclassSearch1extendsLinearList1//顺序查找{publicSearch1(intn)//构造具有n个存储单元的线性表{super(n);create();//线性表中加满随机数}publicSearch1(){this(0);}publicbooleansearch(intk)//查找k值,查找成功时返回true,{//不成功时返回false。intj=1;booleanfind=false;while(!find&
2、&j<=this.length()){System.out.print(this.get(j)+"="+k+"?");if(this.get(j)==k)//判断第j个元素值是否为kfind=true;elsej++;}returnfind;}publicstaticvoidmain(Stringargs[]){intn=8,k=20;Search1s1=newSearch1(n);s1.output();System.out.println("rsearch("+k+")="+s1.search(k));}}程序运行结果:table:2154845912575582
3、1=20?54=20?84=20?59=20?1=20?25=20?75=20?58=20?search(20)=false【例7.2】折半插入排序。本例声明的HalfInsertSort1类继承直接插入排序的InsertSort1类,用折半查找算法覆盖超类中的search顺序查找算法。publicclassHalfInsertSort1extendsInsertSort1//折半插入排序{publicHalfInsertSort1(intn)//构造具有n个存储单元的线性表{super(n);//n个随机数插入排序}publicintsearch(intk)//折半查找k
4、值{//不成功时返回k值应在的位置intleft=1,right,mid=0;right=this.length();while(left<=right)//子序列边界有效{mid=(left+right)/2;if(k5、
6、k>=this.get(mid))mid++;//当k比第mid个元素大时,插入在下一位置returnmid;}publicstaticvoidmain(Stringargs[]){HalfInsertSort1s1=newHalfInsertSort
7、1(8);}}编译时将InsertSort1.class文件存放在当前文件夹中。程序运行结果如下:k=22i=1table:220000000k=80i=2table:2280000000k=33i=2table:22338000000k=78i=3table:223378800000k=4i=1table:422337880000k=52i=4table:4223352788000k=95i=7table:42233527880950k=90i=7table:422335278809095【例7.3】判断单词是否为Java的关键字。程序如下:publicclassIsKe
8、y{Stringtable[]={"abstract","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","extends","false","final","finally","float","for","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protect
9、ed","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","void","while"};IndexNodeindex[]={newIndexNode('a',0),newIndexNode('b',1),newIndexNode('c',4),newIndexNode('d',9),newIndexNode('e',12),newIn