1. Select sort
The principle is to select a minimum (or maximum) number directly from the array to be sorted, each time taking a minimum number,
Put the new array in order until it's all done.
Code Demo:
1 Public classTest3 {2 Public Static voidMain (string[] args) {3 int[] arr = {3, 9, 81, 8, 5, 10 };4 Selectsort (arr);5 print (arr);6 }7 8 /*Select Sort: Principle is the number of comparisons between the first and the remaining elements*/9 Public Static voidSelectsort (int[] arr) {Ten for(inti = 0; i < arr.length-1; i++) { One for(intj = i + 1; J < Arr.length; J + +) { A if(Arr[i] >Arr[j]) { - inttemp =Arr[i]; -Arr[i] =Arr[j]; theARR[J] =temp; - } - } - } + } - + /*post-order print function*/ A Public Static voidPrintint[] arr) { atSystem.out.print ("{"); - for(inti = 0; i < arr.length; i++) { - if(I < Arr.length-1) -System.out.print (Arr[i] + ","); - Else - System.out.print (Arr[i]); in } -System.out.print ("}"); to } +}
The For loop in line 10th controls the total number of comparisons, and the 11th line for loop controls the number of I (minimum or maximum) and the remaining number of comparisons
2. Bubble sort
The principle is that the adjacent number 22 is compared, in order from small to large or from large to small to exchange,
After such a trip, the largest or smallest number was exchanged to the last,
And then start from the beginning to the 22 comparison exchange, until the end of the second place
code example:
1 Public classTest4 {2 Public Static voidMain (string[] args) {3 int[] arr = {3, 9, 81, 8, 5, 10 };4 Bubblesort (arr);5 print (arr);6 }7 8 Public Static voidBubblesort (int[] arr) {9 for(inti = 0; i < arr.length-1; i++) {Ten for(intj = i; J < Arr.length; J + +) { One if(Arr[i] >Arr[j]) { A inttemp =Arr[i]; -Arr[i] =Arr[j]; -ARR[J] =temp; the } - } - } - } + - /*post-order print function*/ + Public Static voidPrintint[] arr) { ASystem.out.print ("{"); at for(inti = 0; i < arr.length; i++) { - if(I < Arr.length-1) -System.out.print (Arr[i] + ","); - Else - System.out.print (Arr[i]); - } inSystem.out.print ("}"); - } to}
Java Basics-Select sort, bubble sort