Java Data structure and algorithm (2)--Java data Structure and algorithm second edition Robert Lafore programming job chapter II __ Data structure

Source: Internet
Author: User
Preface

Recently in the "Java Data structure and algorithms" This book, this book is very good, it is worth looking at. Read the second chapter-an array of articles. So write this chapter summary, just attach oneself write the programming work source code, for everybody reference. A summary in a book Arrays in Java are objects that are manipulated by the new operator. Unordered arrays can provide quick inserts, but lookups and deletions are slow. Encapsulating an array into a class can protect the array from arbitrary changes. The interfaces in a class are made up of methods (and sometimes fields) accessible by the class user. Ordered arrays can be used for binary lookups. A linear lookup takes a proportional amount of time and the number of items in the array. The time required for a binary lookup is proportional to the logarithm of the number of data items in the array. The large O notation provides a convenient way to compare the speed of the algorithm. The large o representation is a comparison that describes how the algorithm's speed is associated with the number of data items. carding knowledge points in an ordered array, if inserted with the binary, insert 20W data, the time of their own test is 43 milliseconds. If you use linear insertion, the time required is very large. The time complexity of the linear insertion is O (n), and the time complexity of the insertion of the binary is O (logn). In an ordered array, the search efficiency is higher than that of linear lookup using the method of linear lookup and binary search. The time complexity of the linear lookup is O (n), and the time complexity of the binary lookup is O (logn). O (1) means that an operation performs a constant of time simple type variables and objects can be stored in an array. after-class coding homework

After class coding homework is still a bit difficult, also spent a long time to write, in this attached source code.

2.1 Adds a method named Getmax () to the Higharray class in the Higharray.java program (listing 2.3) that returns the value of the largest key in the array and returns-1 when the array is empty. Add some code to main () to use this method. You can assume that all the keywords are positive numbers.

2.2 Modifies the method in programming job 2.1 so that it returns not only the largest keyword but also the keyword from the array. Name this method Removemax ().

The Removemax () method in

2.3 Programming Job 2.2 provides a way to sort the array by keyword values. Implement a sort scheme that requires that you do not modify the Higharray class, just modify the code in main (). This method requires a second array, and the array entries are sorted in reverse order at the end of the sort. (This method is a variant of the 3rd Chapter, "Simple Sorting", in which you select a sort.) )

public class Higharray {private long[] A;
    public int size;

    Private Higharrayreversesort Higharrayreversesort; Public Higharray (Higharrayreversesort higharrayreversesort,int initialcapacity) {This.higharrayreversesort=higharr
        Ayreversesort;
        A=new Long[initialcapacity];
    size=0;
        Public boolean find (long findvalue) {int J;
            for (j=0;j<size;j++) {if (a[j]==findvalue) {break;
        } if (J==size) {return false;
        }else{return true;
        } public void Insert (Long value) {a[size]=value;
    size++;
        Public Boolean Delete (Long value) {int J;
            for (j=0;j<size;j++) {if (a[j]==value) {break;
        } if (J==size) {return false;
            }else{for (int k=j;k<size-1;k++) {a[k]=a[k+1];
    }        size--;
        return true;
        The public void display () {A for (int j=0;j<size;j++) {System.out.print ("" +a[j]);
    } System.out.print ("\ n");
        Public long Getmax () {if (size==0) {return-1;
            }else{Long max=a[0];
                for (int j=0;j<size;j++) {if (A[j]>max) {max=a[j];
        } return max;
        } public boolean Removemax () {higharrayreversesort.reversesort (this);
    return Delete (Getmax ());
    public int size () {return size;
    public long get (int index) {return a[index];
        public long set (int index,long value) {Long oldvalue=this.get (index);
        A[index]=value;
    return oldValue; }
}
public interface Higharrayreversesort {public void Reversesort (Higharray array); }
public class higharraytest{public static void Main (string[] args) {Higharray array=new higharray (New Higha 

                    Rrayreversesort () {@Override public void Reversesort (Higharray a) {class inner{
                        public void swap (int m,int i) {long temp=a.get (m);
                        A.set (M, A.get (i));
                    A.set (i, temp);
                    }//TODO auto-generated method stub for (int i=0;i<a.size (); i++) {
                    The maximum value of the small scale int m=i;
                        for (int k=i+1;k<a.size (); k++) {if (A.get (k) >a.get (m)) {m=k; }///If the subscript of the largest element in the sort is equal to I, then the//i is not sorted every time
                    Loops the default maximum element's subscript if (m!=i) {new Inner (). Swap (m,i);
   }             } a.display ();

        }},100);
        Array.insert (23);
        Array.insert (343);
        Array.insert (2543);
        Array.insert (234);
        Array.insert (23);
        Array.insert (233);
        Array.insert (230);
        Array.insert (253);
        Array.insert (223);

        Array.insert (2);


        Array.display ();

        System.out.println ("max =" +array.getmax ());

        Array.removemax ();
    Array.display (); }
}
The 2.4 Modification of the Orderedarray.java program (listing 2.4) makes the insert (), delete () and the Find () method use the binary lookup, as suggested in the book.
public class Orderedarray {private long[] A;

    private int size;
        Public Orderedarray (int inititalcapacity) {a=new long[inititalcapacity];
    size=0;
        public int Linearfind (long searchvalue) {long starttime=system.currenttimemillis ();

        Int J;
            for (j=0;j<size;j++) {if (Searchvalue==a[j]) {break;
            } if (j==size) {long nofoundtime=system.currenttimemillis ();
            System.out.println ("This is a linear query, the number of queries =" +searchvalue+ ", time consuming =" + (nofoundtime-starttime));
        return size;
            }else{long Endtime=system.currenttimemillis ();
            System.out.println ("This is a linear query, the number of queries =" +searchvalue+ ", return index =" +j+ ", Query time =" + (endtime-starttime));
        Return J;
        } public int FastFind (long searchvalue) {System.out.println ("Two-way query");
        Long Starttime=system.currenttimemillis ();
        int start=0;
   int end=size-1;     int mid;
        while (start<=end) {mid= (start+end) >>1;

        System.out.println ("start=", "+start+", end= "+end+", mid= "+mid");
        Long Value=a[mid];
        if (searchvalue>value) {start=mid+1;
        }else if (searchvalue<value) {end=mid-1;
            }else{long Endtime=system.currenttimemillis ();
            System.out.println ("This is a binary query, the number of inquiries =" +searchvalue+ ", return index =" +mid+ ", Query time =" + (endtime-starttime));
        return mid;
        } long Nofoundtime=system.currenttimemillis ();
        System.out.println ("This is a binary query, did not find the number =" +searchvalue+ ", time-consuming =" + (nofoundtime-starttime));
    return-1;
        public void Fastinsert (long insertvalue) {int start=0;
        int end=size-1;

        int mid;

            while (start<=end) {mid= (start+end)/2;

            Long Value=a[mid];

            if (insertvalue>value) {start=mid+1; }else{End=mid-1;
        for (int k=size;k>start;k--) {a[k]=a[k-1];
        } A[start]=insertvalue;
    size++;

        /** * Linear Insert * @param value */public void Linearinsert (Long value) {int J;
            for (j=0;j<size;j++) {if (a[j]>value) {break;
        for (int k=size;k>j;k--) {a[k]=a[k-1];
        } A[j]=value;
        SYSTEM.OUT.PRINTLN ("linear insertion, at this time array size=" +size);
    size++;

        Public Boolean Delete (Long value) {int i=fastfind (value);
        if (i==size) {return false;
            }else{for (int k=i;k<size-1;k++) {a[k]=a[k+1];
            } size--;
        return true;
        The public void display () {A for (int j=0;j<size;j++) {System.out.println ("" +a[j]);
  public int size () {return size;  public void RemoveAll () {size=0;
    public long get (int index) {return a[index]; }
}
public class Orderedarraytest {public static void main (string[] args) {long t1,t2,t3,t4,t5,t6;
        int initialcapacity=400000;
        Orderedarray array=new Orderedarray (initialcapacity);
        The T1=system.currenttimemillis () is inserted into the second Division method.
        for (int i=0;i<200000;i++) {Array.fastinsert (i);
        } t2=system.currenttimemillis ();
        T3=T2-T1;
        SYSTEM.OUT.PRINTLN ("Binary insertion" +array.size () + "strip data, time-consuming =" +t3+ "milliseconds");
        /** Delete 123456** * * * * Boolean flag=array.delete (123456); String msg=flag? "
        Delete succeeded ": Delete Failed";
        System.out.println ("msg=" +msg);
        /*************** linear insertion of ******************/t4=system.currenttimemillis ();
        for (int i=200000;i<400000;i++) {Array.linearinsert (i);
        } t5=system.currenttimemillis ();
        T6=T5-T4;

        SYSTEM.OUT.PRINTLN ("Linear insert" +200000+ "bar data, time-consuming =" +t6+ "milliseconds");
        Long searchvalue=321234; /** binary Query **/int index=array.fastfind (Searchvalue);
    /** linear query **/array.linearfind (searchvalue); }


}
"2.5" adds a merge () method to the Ordarray class of the Orderedarray.java program (listing 2.4), allowing it to combine two ordered source arrays into an ordered array of purposes. Add the code in main (), insert the random number into the two source array, call the merge () method, and display the result destination array. The number of data items in the two source array may be different. In the algorithm, you need to compare the keywords in the source array to select the smallest data item to copy to the destination array. Also consider how to resolve when a source array of data items have been taken out and the other is left with some data items.
public class Neworderedarray extends orderedarray{public neworderedarray (int Inititalcapac
        ity) {super (inititalcapacity); TODO auto-generated Constructor stub} public void Merge (Neworderedarray oldArray1) {Neworderedarray
        Oldarray2=this;
        Neworderedarray newarray=new Neworderedarray (Oldarray1.size () +oldarray2.size ());
        for (int i=0;i<oldarray1.size (); i++) {Newarray.fastinsert (Oldarray1.get (i));
        for (int j=0;j<oldarray2.size (); j + +) {Newarray.fastinsert (Oldarray2.get (j));
    } newarray.display (); @Override public void Display () {//TODO auto-generated a stub for (int j=0;j<this.siz
        E (); j + +) {System.out.print ("" +this.get (j));
    } System.out.print ("\ n"); }


}
public class Neworderedarraytest {public

    static void Main (string[] args) {

        Neworderedarray oldarray1=new Neworderedarray (ten);
        Neworderedarray oldarray2=new Neworderedarray (ten);

        for (int i=0;i<10;i++) {
            Oldarray1.fastinsert (new Random (). Nextint (9999));
            Oldarray2.fastinsert (New Random (). Nextint (666));

        Oldarray1.display ();
        Oldarray2.display ();
        Oldarray1.merge (oldArray2);
    }

"2.6" adds a Nodup () method to the Higharray class in the Higharray.java program (listing 2.3) so that it can delete all duplicates in the array. That is, if the key for three items in the array is the 17,nodup () method, two of them are deleted. You do not have to consider the order in which data items are persisted. One way to do this is to compare each data item to another data item, and then overwrite the duplicate data items with null (or a special value that is not used in the real keyword). Then delete all the null and, of course, reduce the size of the array.
public class Newhigharray extends higharray{public Newhigharray (Higharrayreversesort highAr
        Rayreversesort, int initialcapacity) {super (Higharrayreversesort, initialcapacity);

        TODO auto-generated Constructor stub} public void Nodup (Long value) {//the first method int null=-1;
            for (int i=0;i<size;i++) {if (This.get (i) ==value) {this.set (i,null); for (int j=0;j<this.size (); j + +) {if (This.get (j) ==null) {SYSTEM.OUT.PR
                Intln ("j=" +j);
                for (int k=j;k<size-1;k++) {this.set (k, Get (k+1));
                } size--;
                j--;
            Because of the deletion of an element, the corresponding elements of the J subscript will change, so the j-1 can be properly accessed after the element System.out.println ("size=" +size).
    } this.insert (value); }
}
public class Newhigharraytest {public


    static void Main (string[] args) {

        int initialcapacity=10;
        Newhigharray array=new Newhigharray (New Higharrayreversesort () {

            @Override public
            void Reversesort (Higharray Array) {
                //TODO auto-generated method stub

            }
        },initialcapacity);

        Array.insert (a);
        Array.insert (a);
        Array.insert ();
        Array.insert ();
        Array.insert ();
        Array.insert ();
        Array.insert (m);
        Array.insert (m);
        Array.insert ();
        Array.insert ();

        Array.display ();

        Long  dupvalue=15;
        Array.nodup (dupvalue);

        Array.display ();
    }
Tail words

@ Peas, you have to refuel. If there is a dream, the dream is crazy enough to become a hero, there will always be a story of our legend. May days accompany us to the fore day.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.