Bubble sort of sorting algorithm

Source: Internet
Author: User

The corner does not have three anti-, then no longer------Confucius

Objective

Bubble sort is one of the commonly used sorting algorithms, and the idea of scanning exchange based on bubble sort is a very common design idea in other program design. This article from what is ordered sequence, and then explain the idea of scanning exchange, with examples to guide the reader to understand the bubble sort of design mechanism, so that readers can see around corners, realize the different ideas, more able to do extrapolate.

Starting from the ordered sequence

DS is a structured collection of data items whose structure is reflected in the interaction and interaction between data items. Specifically, it is the logical order between data items. And the sequence as a basic linear structure, its realization mechanism needs us to grasp well. Sorting is widely used as an algorithm to deal with the size relationship between data items. In the sequence, how can a sequence be judged to be orderly? For example sequence A{1 2 3 4 5}, we are at a glance actually ordered (sorted sequence), while sequence b{3 2 4 1 5} is unordered sequence (unsorted sequence). Careful observation is not difficult to find that any pair of pairs of adjacent elements in sequence A are sequential (ordered), such as adjacent elements to 1 2, 2 3, 3 4, 4 5 are sequential, there are adjacent element pairs in sequence B are reverse pairs, such as 3 2, 4 1. That is, in a sequence, if any pair of adjacent pairs are sequential, then the sequence is ordered, and conversely, if there is always a pair of adjacent pairs that are in reverse order, then the sequence is reversed. This conclusion is easy to understand, but gives us some ideas for the next analysis.

Scanning exchange Ideas

Scanning is the sequential comparison of each pair of adjacent pairs, if they are reverse pairs, then exchange the order between two elements to make it a sequential pair. The bubble sort Bubblesort is to sort the sequence based on the scanning interchange. In sequence a of length n, the initial assumption is sorted=true, that is, the sequence is considered unordered, and then during the 1-pass scan, if adjacent reverse pairs (a[i]>a[i+1]) are found, swap swap (a[i],a[i+1]) makes it an adjacent order pair, After such a scan sequence, the largest element must be in a[n-1], that is, after a scan, the unordered sequence length becomes n-1. After the K-Scan, the K-element is ready in a[n-k-1], and the unordered sequence length becomes n-k. The original problem scale is changed from N to n-1 by a scanning switch, which is the reduction strategy.

Code implementation Implementation Algorithm 1
  1. void bubblesort (int a[],int N) //bubble sort a[0 N)
  2. {
  3. for (bool sorted=false; sorted=!sorted; n--) //Repeat scan Exchange, the original problem size minus 1 after each trip
  4. {
  5. for (int j=1;j<n;j++) //left-to-right, pair-check a[0,n) for each adjacent element in the
  6. {
  7. if (A[j-1]>a[j]) //If an adjacent reverse order is found
  8. {
  9. Swap (a[j-1],a[j]); //Exchange
  10. Sorted=false; //Clear global ordered flag at the same time
  11. }
  12. }
  13. }
  14. }

Analysis: According to the method of reduction and treatment, the outer loop continuously reduces the length of the sequence to be sorted, while the global ordered flag is true; in the K-scan, the inner layer loops the N-K elements, and carries on the n-k-1 comparison; If no reverse pair is found in a single scan, the global flag is not assigned a value of false, At this point the outer loop jumps over.

The basic step of the algorithm is to compare and exchange the adjacent element pairs. The time complexity is O (N2), in the best case, the sequence has been ordered, the completion of a scan switch is the end O (n), the worst case, the sequence is completely reverse order, the K-Scan interchange needs to compare n-k-1 times, to perform n-k-1 exchange, Time complexity O (n2)

Based on code Implementation 1 we can separate the scanning algorithm and the bubbling sorting algorithm, and form the following code

Implementation Algorithm 2
  1. void bubblesort (int a[],int lo,int hi) //bubble sort A[lo,hi) left closed right open interval
  2. {
  3. while (! (Bubble (a,lo,hi--))); //scan switching until full order
  4. }
  5. bool Bubble (int a[],int lo,int hi)//Scan interchange A[lo,hi)
  6. {
  7. bool sorted=true;
  8. while (++lo//From left to right, check each pair of adjacent elements individually
  9. {
  10. if (A[lo-1]>a[lo])
  11. {
  12. Swap (A[lo-1],a[lo]);
  13. Sorted=false;
  14. }
  15. }
  16. return sorted;
  17. }
Optimization strategy

For the above two implementations, if for A[0,n], the chaos is limited to a[0, the prefix and suffix length is very different, based on this, first it will be the first scan, and confirm that at the last position an element is already in place (this element is in place), in the suffix, there are a large number of in-place elements , but because there is an exchange in the prefix, Bubble returns false, which is where the algorithm continues to scan until the prefix is fully ordered. In these scans, the original suffix should not be scanned because it is in order, but it still needs to be scanned for R times (R is the prefix length =). This algorithm overall consumes time O (n*r) =o () and should be improved to make it O (n)

Code implementation 3 (improved version)
  1. void bubblesort (int a[],int lo,int hi)//Bubble sort A[lo,hi)
  2. {
  3. while (lo< (Hi=bubble (A,lo,hi))); //per-scan switching, up to full order
  4. }
  5. int Bubble (int a[],int lo,int hi)//Scan interchange A[lo,hi) returns the subscript of the last inverted pair
  6. {
  7. int Last=lo; //rightmost reverse to subscript
  8. while (++lo//From left to right, check each pair of adjacent elements individually
  9. {
  10. if (A[lo-1]>a[lo]) //If reverse order
  11. {
  12. Last=lo; //update rightmost reverse position record
  13. Swap (A[lo-1],a[lo]); //and Exchange
  14. }
  15. }
  16. return last; //Return to rightmost reverse position
  17. }

The algorithm after the change encountered chaos is limited to a[0, only need O (n + O (2)) =o (2n) =o (n) seems to have greatly improved

Summarize

Bubble sort is based on the algorithm of reduction and treatment, the sequencing of sequence is realized by scanning arithmetic, the worst time complexity and average time complexity are O (N2), and the best time complexity is O (n). According to its implementation algorithm, the bubbling sort is a stable sort, because the only adjustment to the position of the element in the bubblesort is that the element a[i-1] is strictly greater than its immediate successor A[i], in this kind of exchange process, the repetition elements can be close to each other, but never cross each other, So bubblesort belongs to the stable sorting algorithm.

Subtotal:

Stable sorting algorithms are: bubblesort (bubbling Sort), insertionsort (insert sort), mergesort (merge sort), Radixsort (base sort)

The unstable sorting algorithm has: Shellsort (Hill Sort) selectionsort (select sort) quicksort (Quick Sort) heapsort (heap sort)

Bubble sort of sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.