Add binaryInsertionSort
This commit is contained in:
parent
325b1d0de9
commit
8c4478ccea
@ -108,7 +108,32 @@ public class IntSorting {
|
||||
* array to be sorted
|
||||
*/
|
||||
public static void binaryInsertionSort(int[] a) {
|
||||
// TODO!!! Your method here!
|
||||
for (int i = 1; i < a.length; i++) {
|
||||
int low = 0;
|
||||
int high = i;
|
||||
int middle = i / 2;
|
||||
|
||||
// Locate insertion point
|
||||
while (low < high) {
|
||||
if (a[i] > a[middle]) {
|
||||
low = middle + 1;
|
||||
} else if (a[i] < a[middle]) {
|
||||
high = middle;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
middle = low + ((high - low) / 2);
|
||||
};
|
||||
|
||||
//Move array and insert value
|
||||
if (middle < i) {
|
||||
int tmp = a[i];
|
||||
for (int j = i - 1; j >= middle; j--)
|
||||
a[j + 1] = a[j];
|
||||
a[middle] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
Loading…
Reference in New Issue
Block a user