Home > php教程 > PHP开发 > body text

Exchange sort—Bubble Sort (Bubble Sort)

高洛峰
Release: 2016-12-19 14:04:00
Original
1381 people have browsed it

Exchange sorting mainly compares the key codes of the records to be sorted in pairs. If the key codes of the records to be sorted occur, if they are contrary to the sorting requirements, then exchange them. Let’s first look at the bubbling process of sorting columns: Let 1

i=1; //Set up pairwise comparison starting from the first record

If i≥j, one-trip bubbling ends.

Compare r[i].key and r[i+1].key, if r[i].key ≤ r[i+1].key, do not exchange, turn to ⑤

when r[i].key> ;r[i+1].key, r[0]=r[i]; r[i]=r[i+1]; r[i+1]=r[0]; change r[i] Exchange

i=i+1 with r[i+1]; adjust the pairwise comparison of the next two records and switch to the ②

bubble sorting method: for a table of n records, the first bubble is A record r[n] with the largest key code, the second bubble is performed on the table of n-1 records, and then a record r[n-1] with the largest key code is obtained. Repeat this until n records are pressed by the key code. Ordered table.


【Algorithm 10.6】


j=n; //Start from the table with n records

If j

i=1; //One trip of bubbling, setting starts from the first record Perform pairwise comparison,

If i ≥ j, one bubbling trip ends, j=j-1; the number of records in the bubble table is -1, go to ②

to compare r[i].key and r[i+1 ].key, if r[i].key≤r[i+1].key, no exchange, turn to ⑤

When r[i].key>r[i+1].key, r[i] r[i+1]; Exchange r[i] and r[i+1]

i=i+1; Adjust the next two records to compare them in pairs, go to ④

【Efficiency Analysis】

Space efficiency: Only one auxiliary unit is used.

Time efficiency: A total of n-1 bubbling operations are required. One bubbling operation for a table with j records requires j-1 key code comparisons.

Number of moves:

Exchange sort—Bubble Sort (Bubble Sort)Best case: the columns to be sorted are already in order, no need to move


Worst case: three moves are required after each comparison,

Exchange sort—Bubble Sort (Bubble Sort)



For more exchange sorting-bubble sorting (Bubble Sort) related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!