Swap sort--bubble sort

Source: Internet
Author: User

Exchange Sorting ideas:

In the unordered area, it was found that two elements were exchanged in reverse order, knowing that they were all ordered.

The interchange sort has a bubbling sort, a quick sort.

Bubble sort Java Implementation:

/**
	 * Bubble sort
	 * @param array to sort data
	 *
	/static void Bubblesort (int[] array) {
		int i, J, Exchange;
		int tmp;
		int n = array.length;
		for (i = 0; i < n-1; i++) {//n-1 bubbling
			exchange = 0;
			for (j = n-1; j > i; j--) {//from back to forward minimum element
				if (Array[j] < array[j-1]) {
					tmp = array[j];
					ARRAY[J] = array[j-1];
					ARRAY[J-1] = tmp;
					Exchange = 1;
				}
			}
			if (Exchange = = 0)
				return;}
	}

Space complexity: O (1)

Complexity of Time:

Positive order, Minimum time complexity: Number of comparisons: n-1, minimum number of moves: 0

Inverse order, Maximum time complexity: comparison: =n (n-1)/2=


Number of moves: =3n (n-1)/2=


Average Time complexity:

The number of comparisons per trip is fixed, but the number of trips is unknown, the average comparison is calculated by substituting the formula.

Bubble sort is a stable 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.