using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/**
* 插入排序
* **/
namespace Algorithm {
class InsertionSort<T> where T:IComparable{
//插入排序
static public void ISort(T[] arr) {
int i, j;
for (i = 1; i < arr.Length; i++) {
if (arr[i].CompareTo(arr[i - 1]) < 0) {
T temp = arr[i];
for (j = i - 1; j>=0 && arr[j].CompareTo(temp) > 0; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = temp;
}
}
}
//二分查找
static public int BinarySearch(T[] arr,int start,int end, T x) {
while (start < end) {
int mid = start + (end - start) / 2 ;
T midData = arr[mid];
if (midData.CompareTo(x) > 0) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return start;
}
//二分查找插入排序
static public void ISortBinarySearch(T[] arr) {
int n = arr.Length;
for (int i = 1; i < n; i++) {
if (arr[i].CompareTo(arr[i - 1]) < 0) {
T temp = arr[i];
int insertIndex = BinarySearch(arr, 0, i, temp);
for (int j = i - 1; j >= insertIndex; j--) {
arr[j + 1] = arr[j];
}
arr[insertIndex] = temp;
}
}
}
static public T[] ISortBSTree(T[] arr) {
BSTree<T> tree = new BSTree<T>(arr);
return tree.ToList().ToArray();
}
}
}
普通插入排序:比较了O(n^2)次,移动了O(n^2)次
二分搜索插入排序:比较了O(nlogn)次,移动了O(n^2)次,时间复杂度仍是O(n^2)
使用二叉树的插入排序:时间复杂度为O(nlgn),达到了基于比较的排序算法的时间下限