Sort algorithm--bubble sort

Source: Internet
Author: User

Package com.java.base.sort.algorithm;/** * Bubble Sort * * <p> algorithm ideas: * * <p>1. Start with the first number of numbers, compare the two numbers per adjacent, and swap the larger (or smaller) number to the back,    Until the largest number is exchanged to the last of the series * * <p>2. The first step in the loop until the first number is left in the sequence. * Algorithm complexity: O (n2) * Stability: Stable * * @author lxy */public class Bubblesort {/**    * Exchange */private static void Swap (int[] array, int m, int n) {int tmp = array[m];    ARRAY[M] = Array[n];  Array[n] = tmp; }/** * Bubble sort: 9,8,11,17,12,2,4,5,20,3,1 */public static int[] Bubblesort (int[] array) {if (array = = NULL | | arra    Y.length = = 0) {throw new IllegalArgumentException ("Array must is not empty!");    } if (array.length = = 1) {return array; } for (int i = array.length-1; i > 0, i--) {for (int j = 0; J < i; J + +) {if (Array[j] > array[        J + 1]) {Swap (array, J, j + 1);  }}} return array;    }/** * Test */public static void main (string[] args) {int[] array = {9, 8, 11, 17, 12, 2, 4, 5, 20, 3, 1};    System.out.println ("bubble sort Before:"); for (iNT i = 0; i < Array.Length;      i++) {System.out.print (array[i]);    System.out.print (",");    } array = Bubblesort.bubblesort (array);    System.out.println ("\ n bubble sort:");      for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]);    System.out.print (","); }  }}

Execution Result:

冒泡排序前:9,8,11,17,12,2,4,5,20,3,1,冒泡排序后:1,2,3,4,5,8,9,11,12,17,20,

Sort algorithm--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.