Java Bubble sort

Source: Internet
Author: User
Tags array length

first, the principle of the algorithm
    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.

    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.

    3. Repeat the above steps for all elements, except for the last one.

    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.

Second, 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.

Third, the code implementation
 Packagesort;Importjava.util.Arrays;/*** Bubble Sort * Compare adjacent elements. If the first one is bigger than the second one, swap them both. * For each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair. At this point, the last element should be the maximum number. * Repeat the above steps for all elements except the last one. * Continue to repeat the above steps each time for fewer elements until there are no pairs of numbers to compare. */ Public classBubblesort { Public Static voidBubblesort (int[] arr) {        Booleanflag=true;  while(flag) {flag=false; inttemp = 0;  for(inti = 0; i < arr.length-1; i++) {                 for(intj = 0; J < arr.length-1-I; J + +) {                    if(Arr[j] > arr[j + 1]) {//Exchange two number of positionstemp =Arr[j]; ARR[J]= Arr[j + 1]; Arr[j+ 1] =temp; Flag=true; }                }                if(!flag) {                     Break; }                }            }        }     Public Static voidMain (string[] args) {inta[]=New int[]{345,22,43,12,65,335,124,636,3};        Bubblesort.bubblesort (a);    System.out.print (Arrays.tostring (a)); }}
View Code

Four, 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).

Five, 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 true, indicating that the sorted table is an unordered table, The flag value is set to True before each sort starts, and the flag is changed to False when the data is exchanged. At the beginning of a new round of sorting, check this flag, if this flag is false, indicates that the last time no exchange data, the end of the sort;

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

 Packagesort;Importjava.util.Arrays; Public classBubblesort { Public Static voidBubblesort (int[] arr) {        Booleanflag=true;  while(flag) {flag=false; inttemp = 0;  for(inti = 0; i < arr.length-1; i++) {                 for(intj = 0; J < arr.length-1-I; J + +) {                    if(Arr[j] > arr[j + 1]) {//Exchange two number of positionstemp =Arr[j]; ARR[J]= Arr[j + 1]; Arr[j+ 1] =temp; Flag=true; }                }                if(!flag) {                     Break; }                }            }        }     Public Static voidMain (string[] args) {inta[]=New int[]{345,22,43,12,65,335,124,636,3};        Bubblesort.bubblesort (a);    System.out.print (Arrays.tostring (a)); }}
View Code

Java Bubble sort

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.