Java-based Bubble Sorting Algorithm and java-based Bubble Sorting Algorithm

Source: Internet
Author: User

Java-based Bubble Sorting Algorithm and java-based Bubble Sorting Algorithm

Algorithm Analysis and Improvement of Bubble Sorting

The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Copy codeThe Code is as follows:
Public class BubbleSort implements SortUtil. Sort {
Public void sort (int [] data ){
Int temp;
For (int I = 0; I <data. length; I ++ ){
For (int j = data. length-1; j> I; j --){
If (data [j] <data [J-1]) {
SortUtil. swap (data, j, J-1 );
}
}
}
}

Bubble Sorting

1. Sorting Method

Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.

(1) initial

R [1. n] is an unordered area.

(2) First scan

The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan

Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note: During the I-th scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example

Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm

(1) Analysis

Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms

Copy codeThe Code is as follows:
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <n; I ++) {// a maximum of N-1 sequential sorting can be performed.
Exchange = FALSE; // The exchange flag should be FALSE before this sort starts.
For (j = n-1; j> = I; j --) // scan the current unordered zone R [I. n] from bottom to top.
If (R [j + 1]. key <R [j]. key) {// exchange Record
R [0] = R [j + 1]; // R [0] is not a sentry, only a temporary storage unit
R [j + 1] = R [j];
R [j] = R [0];
Exchange = TRUE; // The exchange flag is set to TRUE due to exchange.
}
If (! Exchange) // This sort order has not been exchanged, and the algorithm is terminated in advance
Return;
} // Endfor (External Loop)
} // BubbleSort

4. Algorithm Analysis

(1) The best time complexity of the algorithm
If the initial state of the file is in positive order, a scan can complete the sorting. The required keyword comparison times C and record moving times M both reach the minimum value:
Cmin = n-1
Mmin = 0.
The best time complexity of Bubble Sorting is O (n ).
(2) Worst time complexity of Algorithms
If the initial file is in reverse order, n-1 sort is required. For each sort, we need to compare the n-I keywords (1 ≤ I ≤ N-1), and each comparison must move the record three times to reach the position of the exchange record. In this case, the maximum number of comparisons and moves is reached:
Cmax = n (n-1)/2 = O (n2)
Mmax = 3n (n-1)/2 = O (n2)
The worst time complexity of Bubble Sorting is O (n2 ).
(3) The average time complexity of the algorithm is O (n2)
Although the Bubble Sorting does not have to be n-1, the average time performance is much worse than the direct insertion sorting because of the large number of records moving.
(4) algorithm Stability
The Bubble Sorting is in-place and stable.
5. Algorithm Improvement
The above Bubble Sorting can be improved as follows:
(1) Remember the Bubble Sorting of lastExchange where the last exchange occurred
In each scan, remember the last place where the exchange occurred, lastExchange (the adjacent records before this location are ordered ). At the beginning of the next sorting, R [1 .. lastExchange-1] is an ordered area, and R [lastExchange .. n] is an unordered area. In this way, a sorting operation may expand multiple records in the current ordered area, thus reducing the number of sorted records. For specific algorithms, see exercises ].
(2) Change the Bubble Sorting in the Scanning direction
① Asymmetry of Bubble Sorting
When the scanning completes sorting:
Only the lightest bubbles are in the R [n] position, and the rest of the bubbles are sorted in order, so you only need to perform a scan to complete the sorting.
[Example] Only One scan is required for the initial keyword sequence.
N-1 scans are required to complete sorting:
When only the heaviest bubbles are at the position of R [1] and the rest of the bubbles are sorted, you still need to perform n-1 scans to complete the sorting.
[Example] for the initial keyword sequence:, and, a seven-hop scan is required.
② Cause of asymmetry
Each scan can only "sink" the heaviest bubble. Therefore, n-1 scans are required when the heaviest bubble at the top is sunk to the bottom.
③ Method for Improving Asymmetry
Changing the Scanning direction alternately during sorting can improve the asymmetry.
JAVA code:
Copy codeThe Code is as follows:
Package Utils. Sort;

/**
* @ Author Linyco
* Sort the Array Using the Bubble sorting method. The elements in the array must implement the Comparable interface.
*/
Public class BubbleSort implements SortStrategy
{
/**
* Sort the elements in the array obj by the Bubble Sorting Algorithm.
*/
Public void sort (Comparable [] obj)
{
If (obj = null)
{
Throw new NullPointerException ("The argument can not be null! ");
}

Comparable tmp;

For (int I = 0; I <obj. length; I ++)
{
// Remember, the ratio starts from the first one each time. The final comparison is unnecessary.
For (int j = 0; j <obj. length-I-1; j ++)
{
// Compare the adjacent elements. If the backend is small, the elements are exchanged.
If (obj [j]. compareTo (obj [j + 1])> 0)
{
Tmp = obj [j];
Obj [j] = obj [j + 1];
Obj [j + 1] = tmp;
}
}
}
}
}

Related Article

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.