3 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
只是為了給你一個(gè)可能的想法:
public static void insertionSort(int[] array) {
if (array.length <= 1) {
return;
}
// Start with an initially sorted part.
int loSorted = array.length - 1;
//int hiSorted = array.length;
while (loSorted > 0) {
// Take one from the array
int x = array[0];
// Where in the sorted part to insert?
int insertI = insertPosition(array, loSorted);
// Insert x at insertI
...
--loSorted;
}
}

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
謝謝您的意見。我稍微改變了功能,現(xiàn)在似乎可以工作了
` public static void insertSort(int[] array, int lo, int hi){ int mid; 整數(shù)位置;
for (int i = 1; i < array.length; i++) {
int j = i -1;
int x = array[i];
while (lo <= hi) {
mid = lo + (hi -lo)/2;
if (x == array[mid]) {
pos = mid;
break;
}
if (x > array[mid]) {
lo = mid+1;
}
else if (x < array[mid]) {
hi = mid-1;
}
}
while (j >= 0 && array[j] > x) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
問題似乎出在最后一部分,我試圖將元素移動(dòng)到正確的位置。該功能可能并不完美,因此歡迎建設(shè)性批評(píng):)

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
每當(dāng)我需要二分搜索時(shí),我的函數(shù)看起來如下:
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
在您的 main 方法中,調(diào)用如下所示:
public static void main(String[] args) {
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
我希望我能夠幫助你!
添加回答
舉報(bào)