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.