//----- 冒泡: 外层for (int i=0; i<len-1; i++) 内层for (int j=0; j<len-i-1; j++)
//----- 选择排序: 外层for (int i=0; i<len - 1; i++) 内层for (int j=i+1; j<len; j++ //------------------折半查找思想
思路: 先划分空间,再在其空间查找,取中间点,中间点往左,元素的值一定比中间值小,右边的值一定比中间值大. 判断关键点 if (key>arr[mid]) {low = mid+1;} //右半区查找 if (key<arr[mid]){high = mid - 1;} //左半区查找 找12 low high 0 1 2 3 4 5 6 7 8 9 // 3412202123284567100 -------------------------------------------- 1 low mid high 2 low mid high 3 low high
mid = (low + high) / 2 = 4;
a[4] = 21 > 12 --> high = mid - 1 ---> 4 - 1 = 3 mid = (low + high)/2 = 1;
a[1] = 4 < 12 --> low = mid + 1 --> 1+1 = 2 mid = (2+3)/2 --> 2
a[2] = 12 == 12
//折半查找
|