3-17 (sorted)

Sort:

Is to make a string of data, according to one or some of the key size, increasing or decreasing sorting operation.


1. Insertion sort


Direct insertion sort: insert data in an ordered sequence so that the sequence is still in order.

The time complexity is O(N^2), and the best case is O(N).

Space complexity is O(1)

It is a stable sorting algorithm.


Hill sorting: first select an integer gap, divide the data to be sorted into several groups, and sort each group. It is the optimization of direct insertion sort. According to the gap size, a pre-sort is performed first, and then the gap is sequentially changed until it is 1. The sorting is direct insertion sort. The gap must be: gap=gap/n+1; adding 1 is for the gap to be equal to 1.

When gap>1, it is all pre-sorting, when gap=1, it is direct insertion sorting.

Time complexity is O(N^1.3)

It is an unstable sort.


2. Choose sort

Idea: Every time the smallest or largest data is selected from the data to be sorted, it is stored at the beginning of the sequence.


Direct selection sort: very low efficiency,

The time complexity is O(N^2);

The space complexity is O(1);

The sorting algorithm is not stable.


Heap sort: It is sorted by building a heap.

If descending order is required, a small pile is built , and if ascending order, a large pile is built .

Time complexity is O(N*logN)

The space complexity is O(1);

It is an unstable sorting algorithm.



3. Exchange sorting


Bubble sort: compare the data one by one. Each time the comparison is completed, a number will be generated. In its own position, it needs to be compared n-1 times.

The time complexity is O(N^2).

The space complexity is O(1).

Time-stable sorting algorithm.


Quick sort

Time complexity is O(N*logN)

Space complexity is O(logN)

Unstable sorting algorithm.


hoare method (left and right pointer method)

That is, begin and end are moved in sequence. If in ascending order, the beginning section will find the larger and the key, and the end will find the one that is smaller than the key. If you find it, you will exchange it, knowing that begin==end.

Do the key on the far right, go first on the left, do the key on the left, go first on the right. Because of this, it is certain that the last stop position will be exchanged with the key.


Digging method:

It is to find the left/right end as the key to make it a space, find a number on its right/left and insert its pit, so that the position of the inserted data becomes a pit, and then find a number to insert on the left/right. Know that begin==end.



Front and back pointer method

Define two variables prev and cur, cur=begin, prev=begin-1; cur finds a small value, and when it encounters a small value, prev advances by one, and then exchanges the values ​​of cur and prev. When encountering big, cur advances, and prev does not change.




Guess you like

Origin blog.51cto.com/15085121/2663582