1. Bubble Sort Bubble sort
Public classBubblesort { Public Static voidMain (string[] args) {int[] arr = {2,5,7,1,6,4,9}; for(inti = 0; i < arr.length; i++) { for(intj = 0; J < arr.length-1-I; J + +) { if(arr[j]>arr[j+1]){ inttemp = arr[j+1]; Arr[j+1] =Arr[j]; ARR[J]=temp; } } } for(inti = 0; i < arr.length; i++) {System.out.print (arr[i]); //1245679 } }}
Code Explanation: the outer for loop can be considered as a counter: the number of times the inner for loop is controlled.
After each outer ring loop, the largest element is discharged to the last one, so that the next inner Ring Cycle does not have to compare the last two elements, so the number of inner ring loops decreases accordingly.
2. Select Sorting Selection sort
Public classSelectionsort { Public Static voidMain (string[] args) {int[] arr = {2,5,7,1,6,4,9}; intminindex,temp; for(inti = 0; i < arr.length-1; i++) {Minindex=i; for(intj = i+1; J < Arr.length; J + +) { if(arr[j]<Arr[minindex]) {Minindex=J; }} Temp=Arr[i]; Arr[i]=Arr[minindex]; Arr[minindex]=temp; } for(inti = 0; i < arr.length; i++) {System.out.print (arr[i]); //1245679 } }}
3. Insert sorting Insertion Sort
Public classInsertionsort { Public Static voidMain (string[] args) {int[] arr = {2, 5, 7, 1, 6, 4, 9 }; intPreindex, current; for(inti = 1; i < arr.length; i++) {Preindex= I-1; Current=Arr[i]; while(preindex >= 0 && Arr[preindex] >Current ) {Arr[preindex+ 1] =Arr[preindex]; Preindex--; } Arr[preindex+ 1] =Current ; } for(inti = 0; i < arr.length; i++) {System.out.print (arr[i]); //1245679 } }}
4. Hill sort Shell Sort
Public classShellsort { Public Static voidMain (string[] args) {int[] arr = {2, 5, 7, 1, 6, 4, 9 }; inttemp, J; intGap = 1; while(Gap < ARR.LENGTH/3) {Gap= Gap * 3 + 1; } for(Gap > 0; gap = (int) Math.floor (GAP/3)) { for(inti = gap; i < arr.length; i++) {Temp=Arr[i]; for(j = i-gap; J > 0 && arr[j] > temp; J-=Gap) {Arr[j+ Gap] =Arr[j]; } arr[j+ Gap] =temp; } } for(inti = 0; i < arr.length; i++) {System.out.println (arr[i]); //1245679 } }}
5. Merging sort merge
The rear will be updated
Java implementation of ten sort algorithms