高手请进!关于一个二分插入排序的问题。。
我是个新手,我在做一个二分插入排序,代码如下:
public void binarySort(FileInfo fileInfo, int beginIndex, int endIndex) {
int midIndex = (beginIndex + endIndex) / 2;
float nowLength = fileInfo.getSize();
float midLength = bigFiles.get(midIndex).getSize();
float beginLength = bigFiles.get(beginIndex).getSize();
float endLength = bigFiles.get(endIndex).getSize();
if (nowLength > beginLength) {
bigFiles.add(0, fileInfo);
} else if (nowLength < endLength) {
bigFiles.add(fileInfo);
} else if (nowLength > midLength) {
binarySort(fileInfo, beginIndex, midIndex - 1);
} else if (nowLength < midLength) {
binarySort(fileInfo, midIndex + 1, endIndex);
} else {
bigFiles.add(midIndex, fileInfo);
}
}
bigFiles里面有数据,但是就是排序不对。不知道为什么?帮忙看下啊
------解决方案--------------------不知道你要怎么排序,但是你的排序明显有问题,我写了个按照fileInfo的size升序插入的代码
public?void?binarySort(FileInfo?fileInfo,?int?beginIndex,?int?endIndex)?{
int?midIndex?=?(beginIndex?+?endIndex)?/?2;
float?nowLength?=?fileInfo.getSize();
float?midLength?=?bigFiles.get(midIndex).getSize();
float?beginLength?=?bigFiles.get(beginIndex).getSize();
float?endLength?=?bigFiles.get(endIndex).getSize();
if?(nowLength?<?beginLength)?{
bigFiles.add((beginIndex-1)>0?(beginIndex-1):0,?fileInfo);
}?else?if?(nowLength?>=?endLength)?{
bigFiles.add(fileInfo);
}?else?if?(nowLength?>=?midLength)?{
binarySort(fileInfo,?midIndex+1,?endIndex);
}?else{
binarySort(fileInfo,?beginIndex,?midIndex-1);
}
}