Java Foundation------Bubble sort

Source: Internet
Author: User

Import Java.util.Random;

public class Bubblesort {
public static void Main (string[] args) {
1. Randomly generate 10 integers within 100
Int[] Arr=new int[10];
Random ran=new random ();
for (int i=0;i<arr.length;i++) {
Arr[i]=ran.nextint (100);
}

2. Bubble sort
Sort (arr);

 

3. View Final Sort Results

System.out.println (arrays.tostring (arr));
}
Bubble sort
public static void sort (int[] arr) {

  Valid Code 1: The first loop indicates the number of times you need to bubble, because the last number left does not need to bubble, so the whole bubbling process needs to be bubbling: arr.length-1 times.
for (int i=0;i<arr.length-1;i++) { 

   Valid Code 2: The second loop represents the range of data that needs to be bubbled up, because the data that has come out does not need to be bubbling again, so it needs to be excluded.

Because our entire bubbling design idea is that every cycle takes the largest data in the rest of the data to the last place, so the data behind it doesn't need to be bubbling anymore.

So each bubbling range is from the first position to the arr.length-i-1 position.

              Arr.length-i-1:arr.length-1 indicates the total number of bubbles required, I indicates the number of times that has been taken, so arr.length-i-1 indicates the number of times left to take.
for (int j=0;j<arr.length-i-1;j++) {

    Each bubble needs to compare the current data with the data behind him.

The last data obtained through if (arr[j]>arr[j+1]) is sorted in order from small to large

If you want to sort from a large to a small order, you need to write this: if (arr[j]<arr[j+1])
if (Arr[j]>arr[j+1]) {

     If the current data is larger than the data behind it, the two exchange positions, otherwise the position is unchanged.
int TEMP=ARR[J];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
}
}
}
}
}

Java Foundation------Bubble sort

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.