2 回答

TA貢獻1828條經驗 獲得超3個贊
可悲的是,不可原諒的是,你的“教授”提供的代碼在add()
方法中存在一個錯誤,如下:
public?boolean?add(int?pos,?Object?newElement){ ????growBufferIfNecessary(); ????currentSize++; ????checkBounds(pos);? ???????//?rest?of?method
因為checkBounds()
不是首先調用,所以如果pos
超出范圍,currentSize
將增加(并且緩沖區不必要地增長),使實例處于不一致/錯誤狀態。
編碼101:首先檢查參數。
修理:
public?boolean?add(int?pos,?Object?newElement){ ????checkBounds(pos); ????growBufferIfNecessary(); ????currentSize++; ????????//?rest?of?method
要回答您的問題,您必須實現所謂的插入排序。簡而言之,這意味著使用循環迭代所有元素,并在遇到更大元素或到達元素末尾時插入新元素。
請注意,如果您的數組元素尚未排序,則調用insert()
毫無意義。要處理這種情況,您應該考慮拋出IllegalStateException
if 元素無序(您可以在迭代時檢查前一個元素是否不大于當前元素)。

TA貢獻1831條經驗 獲得超10個贊
不完全像插入排序,因為有空值的空閑空間
public void insert( int n ) {
growBufferIfNecessary();
for( int i = 0; i < buffer.length; i++ ) {
if( buffer[i] == null ) {
buffer[i] = n; currentSize++;
break;
}
else if( buffer[i + 1] != null ) {
int n1 = ((Number)buffer[i]).intValue();
int n2 = ((Number)buffer[i + 1]).intValue();
if( n1 < n && n2 > n ) {
System.arraycopy( buffer, i + 1, buffer, i + 2, currentSize - i - 1 ); // line 1
buffer[i + 1] = n; currentSize++; // line 2
break;
}
}
}
}
該add()函數可以替換第 1 行和第 2 行

TA貢獻1875條經驗 獲得超5個贊
感謝大家的幫助和建議。我通過使用 Marco13 建議的代碼讓它工作: https: //codereview.stackexchange.com/questions/36221/binary-search-for-inserting-in-array#answer-36239 希望每個人都有美好的一天并快樂編程。-TJ
添加回答
舉報