Java Implementation bubble sort

Source: Internet
Author: User
Tags array length

First, bubble sort:

Sort an array by using bubble sort

Second, the basic concept:

Compare adjacent two numbers in turn, place decimals ahead, and large numbers behind. That is, in the first trip: first compare the 1th and 2nd numbers, put the decimals before the large number. Then compare the 2nd and 3rd numbers, place the decimal before the large number, and then continue until you compare the last two numbers, put the decimals before the decimal, and put the large number behind. At the end of the first trip, the largest number was put to the last. In the second pass: The comparison is still starting from the first logarithm (because the 1th number is no longer less than the 2nd number due to the 2nd and 3rd number of interchanges), before the decimal, the large number is placed, it is compared to the second-to-last number (which is already the largest in the penultimate position), the second trip ends, Get a new maximum number in the penultimate position (actually the second largest number in the whole sequence). So go on, repeat the above process until the final sort is finished.

Third, the realization of ideas:

With the double loop, the outer loop variable is set to I and the inner loop variable is set to J. If there are n number needs to be ordered, then the outer loop repeats n-1 times, the inner loop repeats n-1,n-2,...,1 times sequentially. Each comparison of the two elements are related to the inner loop j, they can be identified by a[j] and a[j+1], the value of I sequentially,..., n-1, the value of each i,j is 0,1,2,... n-i.

Set the array length to N:
1. Compare the next two data, if the previous data is larger than the data, two data will be exchanged.
2. So that the No. 0 data of the array to N-1 data after one traversal, the largest one of the data is "sink" to the N-1 position of the array.
3. N=n-1, if N is not 0, repeat the previous two steps, otherwise the sort is complete.

Iv. Java Code Implementation:

 Packagebubble sort;Importjava.util.Arrays;/*** Bubble Sort *@authorMmz **/ Public classBubblesort { Public Static voidBubblesort (int[] arr) {        intTemp//define a temporary variable         for(inti=0;i<arr.length-1;i++) {//number of bubbling trips             for(intj=0;j<arr.length-i-1;j++){                if(arr[j+1]<Arr[j]) {Temp=Arr[j]; ARR[J]= Arr[j+1]; Arr[j+1] =temp; }            }        }    }     Public Static voidMain (string[] args) {intArr[] =New int[]{1,6,2,2,5};        Bubblesort.bubblesort (arr);    System.out.println (arrays.tostring (arr)); }}

Five, performance analysis:

If the initial state of the record sequence is "positive order", then the bubbling sort process only needs to be sorted by a single stroke, and the n-1 is not moved, and the record is not shifted, but if the initial state of the record sequence is "reverse", then N (n-1)/2 comparisons and record movement are required. So the total time complexity of the bubble sort is O (n*n).

Six, algorithm optimization:

The shortcomings and improvement methods of bubble sorting method:
First, in the sorting process, after the final sorting, although the data are all sorted complete, but the program can not determine whether to complete the sorting, in order to solve this shortcoming, you can set a flag bit flag, set its initial value to not 0, indicating that the sorted table is an unordered table, The flag value is set to 0 before each sort starts, and the change flag is not 0 when the data is exchanged. At the beginning of a new round of sorting, check this flag, if this flag is 0, indicating that the last time no exchange data, the end of the sort;

 Packagebubble sort;Importjava.util.Arrays;/*** Bubble Sort Improved *@authorMmz **/ Public classBubbleSort1 { Public Static voidBubblesort (int[] arr) {        BooleanFlag =true;  while(flag) {intTemp//define a temporary variable             for(inti=0;i<arr.length-1;i++) {//number of bubbling trips, n-1                 for(intj=0;j<arr.length-i-1;j++){                    if(arr[j+1]<Arr[j]) {Temp=Arr[j]; ARR[J]= Arr[j+1]; Arr[j+1] =temp; Flag=true; }                }                if(!flag) {                     Break;//If no swap occurs, exit the loop                }            }        }    }     Public Static voidMain (string[] args) {intArr[] =New int[]{1,6,2,2,5};        Bubblesort.bubblesort (arr);    System.out.println (arrays.tostring (arr)); }}

Second, in the bubble sort, a scan may have no data exchange, there may be one or more data exchange, in the traditional bubble sorting algorithm and some of the improved algorithms in recent years, only one scan has no data exchange information, the data exchange occurred in the location information is not processed. In order to make full use of this information, it is possible to make a local bubble sort processing for each inverse data pair in a global scan, called the local bubble sort. The local bubble sort and bubble sort algorithm have the same time complexity, and in the case of both positive and reverse order, the required keywords are compared and the number of moves is exactly the same. Because the number of data moves for a local bubble sort and bubble sort is always the same, and the number of keywords required for a local bubble sort is often less than the bubble sort, this means that the local bubble sort is likely to improve the bubble ordering on the average number of comparisons. When the advantage of less comparison is not enough to offset the extra cost of the complexity of the program, the time performance of local bubble sorting is obviously better than bubble sort when the data volume is large. For n unordered data, when we do a bubbling sort, if the K data and the k+1 data are reversed, then the k+1 data is moved to the appropriate position by a forward bubbling sort, which means that the front k+1 data is adjusted to a positive order. Because this bubbling method only bubbles the first k+1 data, so we call it--local bubbling

It is hoped that this article will be helpful to everyone's Java programming.

Java Implementation bubble sort

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: 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.