First, bubble sort
1, principle: Adjacent elements 22 comparison, large back put. The first time is over, the maximum value is at the maximum index.
2. Code:
Public Static voidBubblesort (int[] arr) { for(intx=0; x<arr.length-1; X + +) {//the outer loop control wheel number, altogether to compare (arr.length-1) Wheel for(inty=0; y<arr.length-1-x; y++) {//the outer loop controls the number of comparisons per round, each round comparing (arr.length-1-i) times if(Arr[y] > Arr[y+1]) {//if the preceding element is larger than the following element, the swap position inttemp =Arr[y]; Arr[y]= Arr[y+1]; Arr[y+1] =temp; } } } }
View Code
Second, choose the sort
1, principle: The 0 position of the elements in turn and all the elements behind, compared to the end, 0 position is the smallest element, and then from the 1 position on the back of the element ratio, gradually get from small to large values.
2. Code:
Public classSelectionsort { Public Static voidMain (string[] args) {int[] arr = {2, 5, 8, 3, 6}; Selectionsort (arr); } Public Static voidSelectionsort (int[] arr) { for(inti=0;i<arr.length;i++) {//The outer loop controls which position the number is compared to the number in the back for(intj=i+1;j<arr.length;j++) {//the inner loop controls how many times this number needs to be compared to the subsequent number. if(Arr[i]>arr[j]) {// //This condition is guaranteed to be arranged from small to large, and vice versa from large to small inttemp =Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; } } } for(intm=0;m<arr.length;m++) {System.out.println (arr[m]); } }}
View Code
Summary of common sorting Algorithms (Java edition)