Deep into Java bubble Sorting and selection of the difference between sorting detailed _java

Source: Internet
Author: User
Bubble sort
It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is wrong. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted.
The code is as follows:
Copy Code code as follows:

public class Nums {
public static void Main (string[] args) {
int []nums = {5,4,3,2,1};
for (int i = 0; i < nums.length; i++) {
for (int j = 0; J < Nums.length-i-1; J + +) {
if (Nums[j] > nums[j+1]) {
int temp = Nums[j];
NUMS[J] = nums[j+1];
NUMS[J+1] = temp;
}
}
for (int x = 0;x < nums.length;x++) {
System.out.print (nums[x]+ ",");
}
System.out.print ("\ n");
}
}
}

The output after each round comparison is as follows:
Copy Code code as follows:

1 4,3,2,1,5,
2 3,2,1,4,5,
3 2,1,3,4,5,
4 1,2,3,4,5,
5 1,2,3,4,5,

It is clear from the output that the algorithm flow of the bubble sort is clearly understood.
Select Sort
Each trip selects the smallest (or largest) element from the data element to be sorted, sequentially at the end of the ordered sequence, until all the data elements to be sorted are finished.
The code is as follows:
Copy Code code as follows:

public class Nums {
public static void Main (string[] args) {
int []nums = {5,4,3,2,1};
for (int i = 0; i < nums.length; i++) {
for (int j = 0; J < Nums.length; J + +) {
if (Nums[i] < nums[j]) {
int temp = Nums[i];
Nums[i] = Nums[j];
NUMS[J] = temp;
}
}
for (int x = 0;x < nums.length;x++) {
System.out.print (nums[x]+ ",");
}
System.out.print ("\ n");
}
}
}

You can see from the code that each of the elements in the nums[i] and array is compared for each round of comparisons.
The output after each round comparison is as follows:
Copy Code code as follows:

1 5,4,3,2,1,
2 4,5,3,2,1,
3 3,4,5,2,1,
4 2,3,4,5,1,
5 1,2,3,4,5,

It is also easy to see from the output that it differs from the bubble sort algorithm.

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.