Insert Sort
时间复杂度O(n**2)
最好情况O(n)
最坏情况O(n**2) //倒序数组
空间复杂度O(1) // in-place
经典插入排序
和打poker一样,我们每次摸到新的牌就会把它插入到我们已经排好序的手牌中
我们顺序遍历数组,每次将下一张牌插入到已经排好序的数组中
Python:
def Classical_insert_sort(num_list):
n = len(num_list)
#假设第一个数为已经排好序的数组,我们从第二个数开始遍历
for i in range(1,n):
next = num_list[i]
j = i
while j>0:
if next<num_list[j-1]:
num_list[j] = num_list[j-1]
else:
break
j -= 1
num_list[j] = next
return num_list
Java:
public int[] ClassicalInsertSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int next = a[i];
int j = i;
while (j > 0) {
if (next < a[j - 1]) {
a[j] = a[j - 1];
} else {
break;
}
j--;
}
a[j] = next;
}
return a;
}
插入排序+二分查找 = 二分查找插入排序
当我们寻找插入数字的位置时,用二分查找替代顺序查找可以将查找的时间复杂度从O(N)降为O(logN),所以总的时间复杂度为O(NlogN)
Python:
def Binary_search_insert_sort(num_list):
n = len(num_list)
for i in range(1,n):
next = num_list[i]
move_index = i
#binary search
order_list = num_list[0:i]
length = len(order_list)
left = 0
right = length-1
insert_index = 0
if next >= order_list[length - 1]:
insert_index = length
elif next < order_list[0]:
insert_index = 0
else:
while left < right - 1:
mid = (left + right) // 2 # python中的除法结果默认为浮点数取整数部分时使用 //
if order_list[mid] > next:
right = mid
insert_index = right
else:
left = mid
insert_index = left+1
while move_index > insert_index: # 移动元素,直到待插入位置处
num_list[move_index] = num_list[move_index - 1]
move_index -= 1
num_list[insert_index] = next
return num_list
Java:
public int[] BinarySearchInsertSort(int[] a){
for (int i = 1; i < a.length; i++) {
int next = a[i];
int moveIndex = i;
// binary search
int[] orderedList = new int[i];
System.arraycopy(a, 0, orderedList, 0, i);
int length = orderedList.length;
int left = 0;
int right = length-1;
int insert_index = 0;
if (next >= orderedList[length-1]){
insert_index = length;
}
else if(next < orderedList[0]){
insert_index = 0;
}
else {
while (left < right - 1){
int mid = (left + right) / 2;
if (orderedList[mid] > next){
right = mid;
insert_index = right;
}
else{
left = mid;
insert_index = left+1;
}
}
}
while (moveIndex > insert_index){
a[moveIndex] = a[moveIndex - 1];
moveIndex -= 1;
}
//System.out.println(Arrays.toString(orderedList));
a[insert_index] = next;
}
return a;
}