Bubble Sorting and its optimization

Source: Internet
Author: User

The idea of bubble sort is brute force method. Bubbling, as the name implies, each time a selection of the following element (maximum or minimum) comes up, resulting in an ordered sequence.

public class Bubblesort {public
    void Bubblesort (int[] array) {
        int len = array.length;
        for (int i = 0, i < len-1; i++) {for
            (int j = len-2; J >= i; j--) {
                if (Array[j] > array[j + 1]) {
                    Swap (Array, J, j + 1);
    }}} public void Swap (int[] array, int i, int j) {
        int temp = array[i];
        Array[i] = array[j];
        ARRAY[J] = temp;
    }
}

An improvement to the bubbling sort is to set up an identity flag, whether the tag array is sorted or not, and the remaining loops are no longer required.

public void Bubblesort (int[] array) {
    Boolean flag = true;//Design an identity that marks whether the array has finished sorting and no longer needs to be sorted
    int len = Array.Length ;
    for (int i = 0; (I < len-1) && flag; i++) {
	flag = false;
        for (int j = len-2; J >= i; j--) {
            if (Array[j] > array[j + 1]) {
                swap (array, J, j + 1);
                Flag = True;}}}



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.