Select sort
/ * Implementation principle: Each number of the array is compared to each number behind it, finding the maximum value from itself to the end of the array (here is the minimum value), and swapping it with the most desirable location. Order to achieve the sort * /
@Test
public void Selectsort () {
int[] Nums = new int[] {4,8,5,7,6,2,4,9,5,7,3,5}; //Define a no-array
for (int i = 0; i < nums.length-1; i++) { //because the last digit of the array is not comparable, so take the second to the bottom of the array
for (int j = i+1; J < nums.length;j++) { //because it is a comparison of each number and the number behind it, the comparison starts from the position of the i+1.
if (Nums[i] > Nums[j]) { //control ascending sort, change greater than to less than or descending sort
int temp = Nums[i]; //Swap location Operation
Nums[i] = Nums[j];
NUMS[J] = temp;
}
}
}
System.out.println (arrays.tostring (nums));
}
Bubble sort
/* Implementation principle: Each number of the array is compared to a number next to it, and the larger number of the two numbers is moved to the back.
In this way, the maximum value is moved to the last side for a complete comparison of each trip, thus ascending sorting is possible.
@Test
public void Bubblesort () {
int[] Nums = new int[] {4,8,5,7,6,2,4,9,5,7,3,5}; //Define a no-array
for (int i = 0; i < nums.length-1; i++) { //The first-level loop is the total number of complete comparisons that are required for the control
for (int j = 0; J < nums.length-1-i;j++) { /* Each time the complete comparison, the largest number is moved to the last, so the number of the following is sorted, the comparison is always the previous number. Length-i-1 is because,
The number of I has been moved to the last side, this I number is already sorted, do not compare. 1 is because, the index of the two number of comparisons is J and j+1*/
if (Nums[j] > nums[j+1]) {//Control ascending sort, put greater than change to less than or descending sort
int temp = Nums[j];//Swap location Operation
NUMS[J] = nums[j + 1];
Nums[j + 1] = temp;
}
}
}
System.out.println (arrays.tostring (nums));
}
Select the implementation of sort and bubble sort