Classic algorithm-bubble sort (Java)

Source: Internet
Author: User

Principle: Assigning large values of adjacent elements to the right

Idea: ①1. Compares the first element in the collection or array to the second element and assigns a larger value to the right;

2. Compare the second element to the third one, and the larger value to the right;

.......

(N-1). Compares the N-1 element with the nth element and assigns a larger value to the right;

From this, the maximum value of the element in the set is obtained and assigned to the element n;

② Repeat Operation ① get the new value of the element N-1, and get the new value of the element N-2;

......

Get the value of element 2 and get the value of element 1

Instance:

Sort for arr[5] = {3,5,2,8,1}:

First trip Sort:

3,5,2,8,1;

3,2,5,8,1;

3,2,5,8,1;

3,2,5,1,8;

Second trip sort:

2,3,5,1,8;

2,3,5,1,8;

2,3,1,5,8;

Third trip Sort:

2,3,1,5,8;

2,1,3,5,8;

Sequence Four:

1,2,3,5,8;

This shows: N numbers to sort complete, a total of N-1 sequencing, every I trip to the order of (n-i) times, so you can use the double loop statement, the outer control loop how many times, the inner layer control each trip cycle times, namely:

for (i = 0; i<arr.length-1;i++) {//outer control how many trips to sort

for (j = 0; j<arr.length-1-i;j++) {//The inner layer controls how many times the adjacent element size is judged by the order of each trip

if (Arr[j]>arr[j+1]) {

temp = Arr[j];

ARR[J] = arr[j+1];

ARR[J+1] = temp;

}

}

}

Classic algorithm-bubble sort (Java)

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.