Code implementation:
packagecom.qiusongde;Importedu.princeton.cs.algs4.In;Importedu.princeton.cs.algs4.StdOut; public classInsertionhalfexchange { public Static voidsort (comparable[] A) {intN =a.length; for(inti = 1; I < N; i++) {comparable Temp=a[i]; intj =i; while(j > 0 && less (temp, a[j-1])) {a[j]= A[j-1]; J--; } a[j]=temp;//Show (a); } } Private Static Booleanless (comparable v, comparable w) {returnV.compareto (w) < 0; } Private Static voidExch (comparable[] a,intIintj) {comparable T=a[i]; a[i]=a[j]; a[j]=t; } Private Static voidShow (comparable[] A) {//Print the array, on a single line. for(inti = 0; I < a.length; i++) {stdout.print (a[i]+ " "); } stdout.println (); } public Static Booleanissorted (comparable[] A) { for(inti = 1; I < a.length; i++) { if(less (a[i], a[i-1])) return false; } return true; } public Static voidmain (string[] Args) {//Read strings from standard input, sort them, and Print.string[] A =in.readstrings (); Show (a); Sort (a); assertissorted (a); Show (a); }}
Unit Test Results:
Compare the performance of insertion and insertionhalfexchange:
packagecom.qiusongde;Importedu.princeton.cs.algs4.Shell;Importedu.princeton.cs.algs4.StdOut;Importedu.princeton.cs.algs4.StdRandom; public classSortcompare { public Static DoubleTimerandominput (String alg,intNintT) {DoubleTotal = 0.0; double[] a=Newdouble[n]; for(intt = 0; T < t; t++) { for(inti = 0; I < N; i++) a[i]=Stdrandom.uniform (); total+=time (alg, a); } returntotal ; } public Static Doubletime (String alg, double[] a) {Stopwatch Timer=NewStopwatch (); if(alg.equals ("Selection") ) Selection.sort (a); if(alg.equals ("insertion") ) Insertion.sort (a); if(alg.equals ("insertionhalfexchange") ) Insertionhalfexchange.sort (a); if(alg.equals ("Shell") ) Shell.sort (a); returnTimer.elapsedtime (); } public Static voidmain (string[] Args) {String alg1= "insertion"; String Alg2= "insertionhalfexchange"; intN = 1000; intT = 1000; DoubleT1 =timerandominput (alg1, N, T); Doublet2 =timerandominput (alg2, N, T); stdout.printf ("for%d Random doubles%d trials\n", N, T, alg1); stdout.printf ("%s is%.1fs%s is%.1fs", alg1, t1, alg2, t2); }}
For the random doubles1.1s Insertionhalfexchange is 0.5s
Algorithm (algorithms) version 4th practice 2.1.25