1、先找出要插入点的位置
2、在移动位置
1 #include <iostream> 2 using namespace std; 3 void BInsertSort(int *arr,int length) 4 { 5 for (int i = 1; i <= length - 1;i++) {//从第一个元素开始插入 6 int low = 0; int high = i-1; int key = arr[i]; 7 if (arr[i]<arr[i-1]) {//如果arr[i]<arr[i-1],则寻找要插入的位置 8 while (low <= high) { 9 int mid = (low + high) / 2; 10 if (arr[mid]>key) { 11 high = mid - 1; 12 } 13 else { 14 low = low + 1; 15 } 16 } 17 } 18 //移位 19 for (int j = i-1; j >=low;j--) { 20 arr[j+1] = arr[j]; 21 } 22 arr[low] = key;//也可以为arr[high+1]=key 23 } 24 } 25 int main() 26 { 27 int arr[10] = {9,2,1,4,5,3,7,6,8,0}; 28 BInsertSort(arr,10); 29 for (int i = 0; i < 10;i++) { 30 cout << arr[i] << " "; 31 } 32 return 0; 33 }