Java data structure and algorithm example: Bubble sort Bubble Sort_java

Source: Internet
Author: User
/** * Bubble Sort estimation is a sort method that is mentioned in every algorithm book. 
 * Its basic idea is to the length of the sequence of N, with N trip to arrange it into an ordered sequence. 
 * The 1th trip will be the largest elements in the sequence of the tail, the 2nd trip will be the 2nd large elements in the penultimate position, * that is, each time the largest element is not arranged to bubble to the end of the sequence. 
 * The sorting method is actually divided into two loops, the outer loop: the element to be sorted starts with the 1th element of the array. 
 * Inner Loop: The element to be arranged starts at the 1th element of the array until the end of the array is not queued. 
 * In the inner loop, the position of the two elements is exchanged if the preceding element is encountered larger than the following element. 
* This shows the complexity of the bubble sort is O (n^2)/package Al; The public class Bubblesort {* * * bubble sort Java language is written and can be directly run Input: N number <a1,a2,,an> * Output: An arrangement of input sequences <a1 ', A2 ',, an ', The number of A1 ' <=a2 ' <=<=an ' to be ranked is also called key complexity: O (n^2) Output: 9 * 10 14 14 21 43 50 77 Example: height of a line/public static void M 
    Ain (string[] args) {Bubblesort bubblesort = new Bubblesort (); 
    Int[] elements = {14, 77, 21, 9, 10, 50, 43, 14}; 
    Sort the array bubblesort.sort (elements); 
      Print the sorted array for (int i = 0; i < elements.length i++) {System.out.print (elements[i)); 
    System.out.print (""); }/** * @author * @param array * @return void */public void sort (int[] array) 
{    int I, J; 
    int tmp; for (i = 0; I <= (array.length-1), i++) {//Outer loop for (j = 0; J < (Array.length-1-i); + +) {//I 
          Nner loop if (Array[j] > array[j + 1]) {TMP = Array[j]; 
          ARRAY[J] = array[j + 1]; 
        Array[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.