二分查詢 java實現
阿新 • • 發佈:2019-02-18
<span style="font-family: Arial; font-size: 14px; line-height: 26px;"> 折半排序法(二分插入排序法)</span><br style="font-family: Arial; font-size: 14px; line-height: 26px;" /><span style="font-family: Arial; font-size: 14px; line-height: 26px;">排序原理:其實也屬於插入法型別,分已排序和未排序部分.然後將未排序</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;">部分元素逐個排序插入,但是插入的過程不同,需要每次求一個</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;">中間位置,和中間位置元素比較大小,然後根據大小情況,將高位</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;">左移或者將低位右移,再求中間元素比較,直到找到合適位置後,</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;"> 將其後已排序元素全部後移一位,再插入該勻速即可.此方法中</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;"> 每步列印的high和low關係應為high+1=low</span><span style="font-family: Arial; font-size: 14px; line-height: 26px;"> </span>
public class ErFenSort { public static void main(String[] args) { int[] inte = { 3, 2, 5, 6, 0, 1, 9 }; erfenSort01(inte); int len = inte.length; for (int i = 0; i < len; i++) { System.out.print(inte[i] + " "); } } private static void erfenSort01(int[] inte) { // TODO Auto-generated method stub int low,mid,hight; int temp; for(int i=1;i<inte.length;i++){ temp=inte[i]; low=0; hight=i-1; while(low<=hight){ mid=(low+hight)/2; if(inte[mid]>temp){ hight=mid-1; }else{ low=mid+1; } } for(int j=i-1;j>hight;j--){ inte[j+1]=inte[j]; } inte[hight+1]=temp; } } }