Also for several days did not record the algorithm learning situation, the two days to see the "Introduction to the algorithm," the second part, sequencing and sequencing statistics, record, also by the way to enhance memory
1. Heap Sequencing
is the largest heap and the smallest heap, with a one-dimensional array storage, the data structure is a complete binary tree. The main process is divided into the construction of the maximum/minimum heap, insert operation, Pop maximum, take the maximum/minimum value, change the weight in the heap.
The build heap starts from the first non-leaf node and counts down to the first node, executing the following function (the largest heap for example) for each node:
void heapify (int x)
{
int largest;
if (X*2<=heapsize&&a[x] > A[x * 2]) largest = x;
else largest = x * 2;
if (X*2+1<=HEAPSIZE&&A[X * 2 + 1]>a[largest]) largest = x*2+1;
if (x!=largest)
{
Swap (a[largest],a[x]);
Heapify (largest);
}
}
For each node I, compare it to its two child nodes i*2 and i*2+1, place the largest element in the parent node of the three, and use the function recursively for the node that previously held the largest element to build the largest heap. Time complexity is O (NLGN), for each element, recursive with the maximum depth of the function is LGN, each recursive time complexity is constant, a total of N/2 nodes to execute the function, so the time complexity should be N/2*A*LGN,1/2 and a are constants, omitted to be O (NLGN)
Maximum value: Take out the top element of the heap, the time complexity is O (1)
Change value operation: The book is said to be the increase function, that is, for the maximum heap, only the value of the increase when the change and operation, otherwise do not operate. The operation is as follows: Compare the current element with his father node, if it is larger than the Father node:
void increase (int pos,int x)
{
if (a[pos]<x)
{
A[pos] = x;
while (POS>1&&A[POS]>A[POS/2])
{
Swap (A[POS],A[POS/2]);
pos = POS/2;
}
}
}//x to replace the element of POS position
In fact, for the largest heap, when X<a[pos] is also possible, as long as the call increase function to call the Heapify function can be changed. (Personal understanding)
Add Value: Array length + +, set the end element of the array to negative infinity, call the function increase (length[a],x) to the element, Length[a] The length of the number of a, x is the size to insert.
Popup Maximum: The maximum value + delete the top element of the heap. Swap the top elements of the heap with the elements at the end of the array and heapify the top elements of the heap
Output heap Sort result: cyclic length[a] times popup maximum.
These are the various operations for heap sorting.
Sequencing and sequencing statistics (1)