The implementation of bubble sort, select sort, insert sort
1 PackageHelloWorld;2 3 Public classMain {4 5 Public Static voidMain (string[] args) {6 int[] A = {11, 45, 44, 88, 22, 15, 9 };7 inttemp = 0;8 for(inti = 0; i < a.length-1; i++) {9 for(intj = 0; J < a.length-1-I; J + +)//J starts at 0,Ten { One if(A[j] > a[j + 1]) { Atemp =A[j]; -A[J] = a[j + 1]; -A[j + 1] =temp; the } - } - } -System.out.print ("bubble sort:"); + for(inti = 0; i < a.length; i++) { -System.out.print (A[i] + ""); + } A System.out.println (); at - //More efficient than bubbling - int[] arr = {11, 45, 44, 88, 22, 15, 9 }; - intK = 0; - intTMP = 0; - for(inti = 0; i < arr.length-1; i++) { inK =i; - for(intj = i; J < Arr.length; J + +) { to if(Arr[j] <Arr[k]) { +K =J; - } the } *TMP =Arr[i]; $Arr[i] =Arr[k];Panax NotoginsengARR[K] =tmp; - } theSystem.out.print ("Select Sort:"); + for(inti = 0; i < arr.length; i++) { ASystem.out.print (Arr[i] + ""); the } + System.out.println (); - $ //Space Complexity O (1), Time complexity O (n2) $ int[] C = {11, 45, 44, 88, 22, 15, 9 }; - intTarget; - for(inti = 1; i < c.length; i++) { the intj =i; -target =C[i];Wuyi while(J > 0 && Target < c[j-1]) { theC[J] = c[j-1]; -j--; Wu } -C[J] =Target; About } $System.out.print ("Insert sort:"); - for(inti = 0; i < c.length; i++) { -System.out.print (C[i] + ""); - } A } +}
Operation Result:
Bubble Sort: 9 Each of the selected sorts:9 one-by-one, insert sort:
Bubble sort, select sort, insert sort