Data structure and algorithm Series III (array)

Keywords: Java network

1. introduction

1.1. Why study data structure and algorithm?

Some people say that data structure and algorithm, computer network, and operating system are the same, away from daily development, except for the interview may not be used in this life!

Some people say that I do business development. As long as I am proficient in API, framework and middleware, can not the code I write fly?

So the question comes: Why study data structure and algorithm?

#Reason 1:
	When interviewing, don't be held back by data structure and algorithm
#Reason 2:
	Do you really want to be CRUD Boy all your life
#Reason 3:
	Engineers who don't want to write open source framework and middleware are not good cooks

1.2. How to systematically learn data structure and algorithm?

I think it's better to learn data structure and algorithm. But I have two puzzles:

1. How to start learning?

2. What is there to learn?

Recommended learning methods:

#Learning methods
1. Starting from the foundation, systematic learning
2. More hands-on, each data structure and algorithm is implemented by code
3. Thinking is more important: understand the implementation idea and don't recite the code
4. Combined with daily development, corresponding application scenarios

Learning content recommendation:

There are many data structures and algorithms. Based on the practical principle, we learn classic and common data structures and algorithms

#Learning content:
1. Definition of data structure
2. Definition of algorithm
3. Complexity analysis
4. Common data structure
	Array, linked list, stack, queue
	Hash table, binary tree, heap
	Skip tables and graphs
5. Common algorithms
	Recursion, sorting, binary search
	Search, hash, greed, divide and conquer
	Dynamic planning, string matching

2. test you.

In the previous [data structure and algorithm II (complexity analysis)], we learned time complexity analysis and space complexity analysis. It's simple, is there? So in this article, let's look at the most basic data structure: array. It is also the basis of other data structures, such as sequential queue and sequential stack.

#Test you:
Do you know the linear table?
2. Can you define arrays in your own words?
3. Do you know the characteristics of arrays?
4. Do you know the ArrayList in java?
5. Do you know the best practices of ArrayList?

3. Array characteristics

3.1. Linearity table

The first feature of array is the data structure based on linear table.

Linear List is to organize data into a line. The data on each linear table only has two directions: forward and backward. The data structure based on linear table includes array, linked list, stack and queue.

Figure 1 (array and linked list):

 

Figure 2 (stack and queue):

3.2. Continuous memory space

The second feature of arrays: continuous memory space.

#Memory space continuous
1. If there is an array, the occupied space is 10M
2. Then 10 m memory space is needed to store in the memory
3. If there is a space greater than or equal to 10M in memory, the storage array is successful
4. If there are two blocks of memory:
  4.1. Memory block memory 1 is equal to 6M
  4.2. Memory block memory 2 is equal to 5M
  4.3. Total memory 1 + memory 2 = 11m
  4.4. Although the total memory is 11m > 10m, the result can't store the array
  4.5. Reason: memory block memory 1 and memory 2 are not continuous memory space

3.3. Operation: Search

The third feature of array: high efficiency of index search according to subscript, and time complexity of O(1)

3.4. Operation: inserting

The fourth feature of array: insert operation. In order to keep memory space continuous, data needs to be moved backward. Low efficiency, time complexity O(n)

3.5. Operation: delete

The fifth feature of array: delete operation. In order to keep memory space continuous, data needs to be moved forward. Low efficiency, time complexity O(n)

3.6. Application case: ArrayList

In the ArrayList of java development, do we see you every year, every month and every day? Then:

#About ArrayList (see discussion and sharing for answers)
1. Do you know that the bottom layer is actually an array?
2. Do you know the reason for its existence?
3. Do you know its recommended usage?

Core source 1:

1. The bottom layer of ArrayList is based on array implementation

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
     /*
     * Default initial capacity.(Initial capacity)
     */
    private static final int DEFAULT_CAPACITY = 10;
    /**
    *Default empty array
    */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    /**
    *Bottom array
    */
     transient Object[] elementData;
    
    /**
    *Construction method, specifying initial capacity
    */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructor, default empty array
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
    ......
    
}

Core source 2:

1. To add an element, first check whether expansion is needed

2. After each expansion of ArrayList, the new space is 1.5 times the original space

3. Conclusion: the reason for the existence of ArrayList supports dynamic expansion

/**
*Additive elements
*/
public boolean add(E e) {
       // Confirm whether the space needs to be expanded
        ensureCapacityInternal(size + 1);  
        elementData[size++] = e;
        return true;
}


/**
*Expansion space
*/
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
    	// New space = old capacity + expansion space ((oldCapacity > > 1))
    	// Expansion space = (oldcapacity > > 1), move 1 bit to the right, that is, divide by 2
    	// Conclusion: after each expansion of ArrayList, the new space is 1.5 times of the original space
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

4. Discussion and sharing

#Test your answer:
1.Do you know the linear table?
  1.1.Linear table ( Linear List),Is to organize the data into a line
  1.2.For data on each linear table, there are only forward and backward directions
  1.3.Data structure based on linear table: array, linked list, stack, queue
  
2.Can you define an array in your own words?
  2.1.Arrays are data structures based on linear tables
  2.2.It's a continuous set of memory spaces
  2.3.Used to store data of the same data type
  
3.Do you know the characteristics of arrays?
  3.1.Based on linear table
  3.2.Memory space continuous
  3.3.Store data of the same data type
  3.4.High efficiency and time complexity of index searching based on subscript O(1)
  3.5.Low efficiency and time complexity of insertion and deletion O(n)
  
4.You know, java Medium ArrayList Do you?
  4.1.ArrayList The bottom layer is based on array implementation
  4.2.The reason for its existence is that it has more functions and supports dynamic capacity expansion
  4.3.After each expansion, the new storage space is 1% of the original space.5 times
  
5.You know, ArrayList Best practices?
  5.1.Because ArrayList The bottom layer is array, in order to keep the memory space continuous
  5.2.After each expansion, data must be copied from the original array to the new array
  5.3.Need extra temporary storage space, low efficiency of copying data
  5.4.In actual development, if the scope of storage elements can be estimated in advance, such as 90...100
  5.5.Then creating ArrayList Object, you can specify the initial capacity of 100, that is:
     ArrayList list = new ArrayList(100);
  5.6.The execution efficiency is the best

Posted by shatteredroses on Sat, 22 Feb 2020 19:54:12 -0800