Bubbling, simple selection, direct insertion these three sorts are simple sorts.
Tool Class
package Utils;import java.util.Arrays;publicclass SortUtils { publicstaticvoidswap(int[] a,int i,int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } publicstaticvoidprintString(int[] a){ System.out.println(Arrays.toString(a)); }}
Bubble Sort
PackageBubblesort;ImportJava.util.Arrays;ImportUtils.sortutils; Public class Demo02 { Public Static void Bubblesort(int[] a) {intlen = a.length;BooleanFlag =true; for(intI=0; i<len-1&& Flag; i++) {flag =false;//Assuming no Exchange for(intj=0; j< len-1-I.; J + +) {if(a[j+1]<A[J]) {flag =true;//Swapped outSortutils.swap (a,j+1, j); } } } } Public Static void Main(string[] args) {int[] A = {2,3,5,4,1,6,9,8,7}; Bubblesort (a); Sortutils.printstring (a); }}
Simple Selection Sorting
PackageSimplesort;ImportJava.util.Arrays;ImportUtils.sortutils; Public class Demo { Public Static void Simplesort(int[] arr) {intMin for(inti =0; i < arr.length; i++) {min = i;//Assuming the first data is the smallest data for(intj = i+1; J < Arr.length; J + +) {if(Arr[min]>arr[j]) {min = j; } }if(i!=min) {Sortutils.swap (arr, Min, i); } } } Public Static void Main(string[] args) {int[] A = {2,3,5,4,1,6,9,8,7}; Simplesort (a); Sortutils.printstring (a); }}
Direct Insert Sort
PackageInsertsort;ImportUtils.sortutils; Public class Demo { Public Static void Insertsort(int[] a) {intTemp,j; for(inti =0; I < a.length-1; i++) {if(a[i]>a[i+1]){//After one data is less than the previous datatemp = a[i+1];//Insert buffer for(j = i; j>=0&&a[j]>temp; j--) {a[j+1] = A[j];//Move backwards}//Because the judgment is made after the previous minus one, so add aa[j+1] = temp; } } } Public Static void Main(string[] args) {int[] A = {2,3,5,4,1,6,9,8,7}; Insertsort (a); Sortutils.printstring (a); }}
compare three kinds of sorting
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Bubble, simple selection, direct insert sort comparison (Java edition)