Java implementation bubble Sort algorithm and its simple optimization example _java

Source: Internet
Author: User

Principle

Bubble sort is probably the algorithm that all programmers use, and one of the most familiar algorithms.
Its ideas are not complicated:
Set now to sort the array arr[], it has n elements.
1. If n=1: Obviously no platoon. (In fact, this discussion doesn't seem necessary)
2. If n>1:
(1) We start with the first element, compare every two adjacent elements, if the previous element is larger than the back, then in the final result the former must be in the back. So, we exchange these two elements. It then makes a comparison of the next two adjacent elements. So until the last pair of elements is finished, the first-round sort completes. To be sure, the last element must be the largest in the array (because each time the relatively large is placed behind).
(2) Repeat the above process, this time we do not need to consider the last one, because it has been lined up.
(3) So until only one element is left, the element must be minimal, then our order can be ended. Obviously, a n-1 order was made.
In this process, each time (or "wheel") sort there is a number that slowly "floats" from one position to the final position (drawing a schematic, drawing the array vertically to see), like bubbling, so it is called "bubble sort".

Code implementation:

 public class bubblesort{public static void Main (string[] args) {int score[] = {
     67, 69, 75, 87, 89, 90, 99, 100}; for (int i = 0; i < score.length-1 i++) {//MAX do n-1 trip sort for (int j = 0; J < score.length-i-1; j +) {//to current  Unordered interval score[0......length-i-1] sort (The range of J is critical, this range is actually shrinking) if (Score[j] < Score[j + 1]) {//switch small value to back int
           temp = Score[j];
           SCORE[J] = score[j + 1];
         Score[j + 1] = temp;
       } System.out.print ("First" + (i + 1) + "Order Result:");
       for (int a = 0; a < score.length a++) {System.out.print (Score[a] + "\ t");
     } System.out.println ("");
       } System.out.print ("Final sort result:");
     for (int a = 0; a < score.length a++) {System.out.print (Score[a] + "\ t"); }
   }
 }


Algorithm Performance/complexity
We ignore the time that the loop variable has been added and initialized. First, analyze the number of times the algorithm is compared. It is easy to see that the above kind of bubble sort without any improvement regardless of how input data will be n-1 wheel sort, and the number of times each round needs to be compared from n-1 to 0. Then, the total number of comparisons is (n-1) + (n-2) +...+2+1 = (n-1) n/2≈ (n^2)/2. (Because I do not know how to play square here, here, I use n^2 to represent the square, the same below)
Let's look at the number of assignments. The assignment here refers to the exchange operation in which, for the above code, 1 exchanges equals three times assignment. Because you do not have to swap every time, the number of assignment operations is related to the input data. In the best case, that is, in the first order, the number of assignments is 0. In the worst-case scenario (worst case), the number of assignments is (n-1) n/2. Assuming that the input data is evenly distributed (or "completely random"), then there are approximately half of the number of exchanges. From the result above, the average condition (average case) can be obtained under the assignment number of 3/2 * (n^2)/2 = 3/4* (n^2).
In summary, in any case, the bubble sort space complexity (extra space) is always O (1).

Improved
when the data is in perfect order, the optimal time complexity is shown, which is O (n). In other cases, almost always O (n^2). Therefore, the algorithm has the best performance in the case of basic data order.
But how does the above code appear to be O (n) complex? In fact, because the above is focused on the basic idea, so just the simplest case, to make the algorithm in the best case of O (n) complexity, need to do some improvement, the improved code is:

public static void Bubblesort (int[] arr) {
  int temp = 0;
  Boolean swap;
  for (int i = arr.length-1 i > 0; i) {//each time the length of the order required
    Swap=false;
    for (int j = 0; J < i; ++j) {//From first element to element
      if (Arr[j] > arr[j + 1]) {
        temp = arr[j];
        ARR[J] = arr[j + 1];
        Arr[j + 1] = temp;
        Swap=true
      }
    } Loop J
    if (Swap==false) {break
      ;
    }
  } Loop I
}//method bubblesort

In fact, because of the almost no bubble sort in the case of large amounts of data, the addition of Boolean variables with small data creates additional overhead. So personally think that the improved algorithm above is purely theoretical, usually, bubble sort to write the previous one on the line.

Algorithm stability
It is easy to see that when the adjacent elements are equal, we do not need to exchange their positions, so the bubble sort is a stable sort.

Algorithm applicable to the scene
Bubble Sort idea is simple, the code is simple, especially suitable for small data sorting. However, because of the high complexity of the algorithm, it is not suitable to use when the data volume is large. If you have to use more data, it's best to improve the algorithm, such as selecting a sorting method.

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.