I have encountered many sorting algorithm problems during my recent interview.
The defined array is as follows:
int[] array = new int[]{4, 1, 8, 2, 5, 6};
First, insert sorting:
/*** Insert sort * @ Param A */Private Static void insertsort (INT [] A) {system. out. println ("insert sorting process:"); For (INT I = 1; I <. length; I ++) {int temp = A [I]; Int J = I-1; while (j> = 0 & A [J]> temp) {A [J + 1] = A [J]; j --;} A [J + 1] = temp; system. out. print ("Step" + I + ":"); printarray (a);} system. out. println ("insert sorting result:"); printarray ();}
Running result:
Insert sorting process:
Step 2: 1 4 8 2 5 6
Step 2: 1 4 8 2 5 6
Step 1: 1 2 4 8 5 6
Step 1: 1 2 4 5 8 6
Step 1: 1 2 4 5 6 8
Insert the sorting result:
1 2 4 5 6 8
Hill sorting implementation:
Private static void shellInsertSort (int [] a, int start, int dk) {int I, j; for (I = start + dk; I <. length; I + = dk) {j = I-dk; int temp = a [I]; while (j> = 0 & a [j]> temp) {a [j + dk] = a [j]; j-= dk;} a [j + dk] = temp;} System. out. println ("sorting result:"); printArray ();}
Bubble Sorting implementation:
/*** Bubble sort * @ param a */private static void bubbleSort (int [] a) {System. out. println ("Bubble sorting process:"); for (int I = 0; I <. length; I ++) {for (int j = 0; j <. length-I-1; j ++) {if (a [j]> a [j + 1]) {int temp = a [j]; a [j] = a [j + 1]; a [j + 1] = temp;} System. out. print ("Step" + (I + 1) + ":"); printArray (a);} System. out. println ("Bubble sorting result:"); printArray ();}
Running result:
Bubble sorting process:
Step 2: 1 4 2 5 6 8
Step 1: 1 2 4 5 6 8
Step 1: 1 2 4 5 6 8
Step 1: 1 2 4 5 6 8
Step 1: 1 2 4 5 6 8
Step 1: 1 2 4 5 6 8
Bubble sorting result:
1 2 4 5 6 8
Improved Bubble Sorting Algorithm:
Private static void bubbleSortBetter (int [] a) {System. out. println ("Improved Bubble sorting process:"); boolean bool; int I = 0; do {bool = false; for (int j = 0; j <. length-I-1; j ++) {if (a [j]> a [j + 1]) {int temp = a [j]; a [j] = a [j + 1]; a [j + 1] = temp; bool = true;} I ++; System. out. print ("Step" + I + ":"); printArray (a);} while (bool = true & I <. length); System. out. println ("Improved Bubble sorting result:"); printArray ();}
Running result:
Improved Bubble sorting process:
Step 2: 1 4 2 5 6 8
Step 1: 1 2 4 5 6 8
Step 1: 1 2 4 5 6 8
Improved Bubble sorting result:
1 2 4 5 6 8
Compare the visible effect with the previous algorithm.
Please leave a message if you have any questions!
Note: Please indicate the source for reprinting.