代码实现
直接插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public void sort(int l,int r){ int tmp; for (int i = l+1,j; i <= r; i++) { tmp = data[i]; for ( j = i; j >0; j--) { if(data[j-1]>tmp){ data[j]=data[j-1]; }else { break; } } data[j]=tmp; } }
|
折半插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| private int lookForIndex(int l, int r, int val){
int bl=l,br=r; int index=br; if(data[r]<=val){ return -1; }else if(data[l]>val){ return 0; } while (bl<br){ index = (bl+br)/2; if(data[index]>val){ br=index; }else { bl=index+1; } } index = br; return index; }
public void sortByBinary(int l,int r){ int tmp,index; for (int i = l+1; i <= r; i++) { tmp = data[i]; index = lookForIndex(l,i-1,tmp); if(index<0){ continue; } for (int j = i; j >index; j--) { data[j]=data[j-1]; } data[index]=tmp; System.out.println(l+" "+i+" "+index+" "+Arrays.toString(data)); } }
|
请我一杯咖啡吧!
微信打赏
0%