import java.util.Arrays;
public class InsertSort {
public static void main(String[] args) {
int[] nums = new int[]{4,9,6,3,5,123,45};
insertSort4(nums);
System.out.println(Arrays.toString(nums));
}
public static void insertSort(int[] nums){
for (int begin=1;begin<nums.length;begin++){
int index=begin;
for (int end=begin-1;end>=0;end--){
if (nums[end]>=nums[index]){
int temp = nums[index];
nums[index] = nums[end];
nums[end] = temp;
index=end;
}else {
break;
}
}
}
}
public static void insertSort2(int[] nums){
for (int begin=1;begin<nums.length;begin++){
int index=begin;
int temp = nums[begin];
for (int end=begin-1;end>=0;end--){
if (nums[end]>=nums[begin]){
index--;
}else {
break;
}
}
for (int i=begin-1;i>=index;i--){
nums[i+1]=nums[i];
}
nums[index] = temp;
}
}
public static void insertSort3(int[] nums){
for (int begin=1;begin<nums.length;begin++){
int index=begin;
int temp = nums[begin];
for (;index-1>=0&&nums[index-1]>temp;){
nums[index] = nums[index-1];
index--;
}
nums[index] = temp;
}
}
public static void insertSort4(int[] nums){
for (int begin=1;begin<nums.length;begin++){
int temp = nums[begin];
int insertPosition = search(nums,begin);
for (int i=begin-1;i>=insertPosition;i--){
nums[i+1]=nums[i];
}
nums[insertPosition] =temp;
}
}
public static int search(int[] nums,int index){
int begin = 0;
int end = index;
while (begin<end){
int mid = (begin+end)>>1;
if (nums[index]<nums[mid]) end = mid;
else begin=mid+1;
}
return begin;
}
}