Java Data Structures and Algorithms (ii) # # arrays

Source: Internet
Author: User

Directory

    • Array overview
    • Arrays in Java
      • Create an array
      • accessing arrays
      • Initializing an array
      • Ordered array
      • Linear Lookup
      • Two-point Search
      • Advantages and disadvantages of ordered arrays
    • Large O notation (order of)
    • Why not use data to solve everything
-Summary of the array

Array is the most extensive data storage structure, there is a special array (ordered array), the following explanation of INSERT, query, delete related considerations

    • Insert: New data is always inserted in the first slot of the array, because the number of data items already known, so the location of the vacancy is easy to know, but the query and delete is not so fast. When you do not allow the insertion of duplicate values in the mode, you also need to calculate whether the algorithm has data items.
    • Lookup: If there is no recurrence pattern, you must search for half of the data items on average to find specific data items. Find the data item of the array head fast, look for the data item at the end of the array is slow. If you repeat the pattern, you must find the tail from scratch.
    • Delete: A specific data item cannot be deleted until it is found (either the data item is replaced or becomes empty). The deletion algorithm assumes that no holes are allowed (there are non-empty data items behind one or more empty cells), and if the deletion algorithm allows holes, the other algorithms become complex because the non-airborne inefficiencies are judged. Therefore, non-empty data items must be contiguous and cannot have holes. Find the average N/2 data item + Move the remaining N/2 data items to fill the hole in the No Duplicates mode. A total of n steps.
    • Duplicate value problem:
      • Lookup algorithms in duplicate mode: Duplicates make the lookup algorithm complex, and after matching the previous one, it is also important to consider whether to continue looking for possible matches until the last data item (the difference between the blue-eyed person and the first blue-eyed person). Usually the operation requires n steps.
      • Insert algorithm in duplicate mode: As with the non-repeating item pattern, only one step is required.
      • Delete algorithm in duplicate item mode: If delete the first specific data item, the operation step is N/2 to find +N/2 move, if delete all specific data item, need to check N data item + Move extra N/2 data item, the average time of operation depends on number and distribution of duplicates.

Differences between table-repeating and non-repeating patterns

Operation Duplicate not allowed Allow duplicates
Find N/2 Times Comparison N-Times comparison
Insert No comparison, one move One move
Delete N/2 times comparison, N/2 moves N-times comparison, more than n/2 moves
Arrays in Java Create arrays

int[] intArray = new int[]{};
int[] intArray = new int[2];

accessing arrays

Array data items are accessed by subscript, with the subscript starting at 0, ending with a length minus 1. If the subscript does not access the array in this range, the run-time error of the array Index out of bounds is thrown.

Initializing an array

int[] intArray = {1,2,3,4,5};
int[] intArray = new int[]{1,2,3,4,5};

code example

GitHub Address

public class HightArray {    /** 声明一个数组 */ private long[] a;    /** 声明变量记录数据项个数 */ private int nElemts;    /** 构造方法用于初始化数组和数据项总数 */    public HightArray(int max){ a = new long[max]; nElemts = 0; }    public void insert(long value){ a[nElemts] = value; nElemts ++ ; }    public boolean find(long searchKey){        int j;        for (j=0;j<nElemts;j++){ if(a[j]==searchKey){ break; } }        return j == nElemts;    }    public boolean delete(long value){        int j;        for (j=0; j<nElemts; j++){ if(a[j]==value){ break; } }        if(j == nElemts) { return false; }        else {            for (int k=j; k<nElemts; k++){ a[k] = a[k+1]; }            nElemts--;            return true;        }    }    public void display(){                   System.out.println(Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(" ")));    }}

Test class >>>

public class HightArrayTest {    @Test public void test(){        int maxSize = 100;        HightArray hightArray = new HightArray(maxSize){{            insert(77); insert(99); insert(44); insert(55); insert(66);            insert(22); insert(88); insert(11); insert(00); insert(33);        }};        hightArray.display();        int searchKey = 35;        System.out.println(hightArray.find(searchKey)?"Found ":"Can‘t find " + searchKey);        hightArray.delete(00); hightArray.delete(55); hightArray.delete(99);        hightArray.display();    }}
Ordered array

The data items in the array are sorted in ascending order by keyword. When inserting a data item into this array, you need to find the correct position for the insert operation, between a slightly smaller position and a slightly larger position, and then move a slightly larger position to the end of the data item to make a free position.
The advantage of this sequential arrangement is that the query speed can be significantly improved by binary search, but the speed of insertion is reduced, and the pit position is freed after all.

Linear Lookup

A linear lookup is a search for a match, in turn. In an ordered array, the lookup is exited when a suitable data item is matched.

Two-point Search

Binary search is half the search, which is much faster than linear queries, especially for large arrays.

Example of an ordered array code

GitHub Address

public class Orderarray {private long[] A;    private int nelems;    Public Orderarray (int maxSize) {a = new long[maxsize]; nelems = 0;}    public int size () {return nelems;}        public void Insert (Long value) {int J;        for (j = 0; J < Nelems; J + +) {if (A[j] > value) {break;}}        for (int k=nelems; k>j; k--) {a[k] = a[k-1];}        A[J] = value;    nelems++;        } public int find (long searchkey) {int lowerbound = 0, Upperbound = nElems-1, curindex;            while (true) {if (Lowerbound > Upperbound) {return nelems;}            Curindex = (lowerbound + upperbound)/2;            if (a[curindex] = = Searchkey) {return curindex;}            else if (A[curindex] < Searchkey) {lowerbound = Curindex + 1;}        else {upperbound = curIndex-1;}        }} public Boolean delete (Long value) {Int J = find (value);        if (j = = Nelems) {return false;} for (int k = j; k < Nelems; k++) {a[k] = a[k+1];}        nelems--;    return true; The public void display () {System.out.println (Arrays.stream (a). Maptoobj (string::valueof). Collect (Collectors.joinin    G (""))); }}

Test class >>>

public class OrderArrayTest {    @Test public void test(){        int maxSize = 100;        OrderArray orderArray = new OrderArray(maxSize){{            insert(77); insert(99); insert(44); insert(55); insert(22);            insert(88); insert(11); insert(00); insert(66); insert(33);        }};        int searchKey = 55;        System.out.println(orderArray.find(searchKey)!=orderArray.size()?"Found":"Can‘t find" + searchKey);        orderArray.display();        orderArray.delete(00); orderArray.delete(55); orderArray.delete(99);        orderArray.display();    }}
Advantages and disadvantages of ordered arrays
    • Pros: Binary lookup is faster than unordered data.
    • Disadvantage: Insert need to find, after looking for the back of the data items to move the whole backwards. The delete operation requires a hole to fill.
Large O notation (order of)
algorithm Run Time
Linear lookup (from beginning to end) O (N)
Binary search (half of half) O (LOGN)
Unordered array insertion (one time only) O (1)
Sequential array insertion (query + move) O (N)
Unordered array Delete (query + fill hole) O (N)
Ordered array deletion (query + fill hole) O (N)
Why not use data to solve everything

An unordered array is inserted (O (1) time), and the query spends (O (N) time). An ordered array query spends (O (logn) time), but inserts a missing cost (O (N) time). And the deletion takes (O (N) time). So a data structure needs to be inserted, queried, deleted quickly, theoretically (O (1) or O (logn) time), and once the array is created, its size is fixed, the expansion is inconvenient, if the space is large and will be wasted.

Summary
    • Unordered arrays can be inserted quickly, but queries and deletions are slow.
    • An ordered array can be found using the dichotomy method.
    • Linear lookups require a proportional amount of time and number of data items.
    • The dichotomy is proportional to the logarithm of the number of data items needed to find the time.
    • O (1) algorithm is best, O (logn) Second, O (N) General, O (n*n) the worst.

Java Data Structures and Algorithms (ii) # # arrays

Related Article

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.