Sorting algorithms: bubble sort and selection sort

Sorting algorithm and effect principle : the array values, according to the order of execution, ordered from small to large.

A bubble sort
principle : two adjacent unit, comparing the stored data, if the first data unit is large, it will be two adjacent cells, the exchange data is stored.

Process : start from the initial comparison unit, the first cycle will be selected by a maximum value, and finally all of the cells on the array, each cycle will then compare the present cycle a maximum value, the comparison unit participating in the current Finally, comparing previously selected unit, a relatively lower will not participate.

Optimization :
1, a single cycle, the last unit, the penultimate units, the last unit involved in comparison, do not participate in a single cycle;
2, before the comparison of the maximum value, the longer time involved in the comparison
3, n units, as long as the comparison cycle n-1 times, and finally a unit, not recycled comparison

Core : exchanging data stored in two adjacent cells, comparing the data size, the larger value the first unit, the two units exchanged data stored

For example: for loop, each loop implement sorting to find a current maximum, multiple cycles to complete sorting
Here Insert Picture Description
Second, select the ordering
principle and procedure : the cycle starting position to define a minimum value of the default location, from a starting position the next execution cycle start position, if the location has a value less than the value in the storage position of the index, the index value is stored in this position, the end of the cycle, comparing the stored indexes are the index start position, if not, to swap the two value at the position of the minimum value of the present cycle will be placed at the start of the cycle, and then perform multiple cycles to complete the order.

Core : find the index value exchanged with the starting position of the minimum value, first find the index value exchanged

Optimization of the outer layer : the value before the comparison, without participation of a comparator;
inner Optimization : start the cycle from the next position of the start position

For example: for loop to achieve selection sort
Here Insert Picture Description
Bubble sort selection and sort advantages and disadvantages:

Bubble sort : each occurrence of the issue order of the data exchange operation to be performed, the number of data exchange is performed, the above selection sort.
Selection sort : If the order of occurrence of the problem, but do assignment indexing operation, and so the cycle is completed, judgment is performed, to make a data exchange, the data exchange operation is relatively cumbersome, too execution times and low efficiency.

Released seven original articles · won praise 0 · Views 78

Guess you like

Origin blog.csdn.net/weixin_43310703/article/details/105010588