ソートされたリストに挿入するオブジェクトのインデックスを再帰的に返す検索メソッドを実装しようとしています。新しいアイテムがソートされたリストの中に入る場所を再帰的に検索しますか?
ここは私の試みです。
//listSize is the number of elements inside the sorted list
//sortedList is the actual structure holding the values
// Note: the parameter Value is comparable.
public int search(T value,int index){
if(listSize == 0){
return 0;
}
if(index > listSize){
return listSize+1; //add at the end
}
if(value.compareTo(sortedList[index]) > 0 && value.compareTo(sortedList[index+1]) < 0){
//value is less
return index+1;
}else if(value.compareTo(sortedList[index]) == 0){
//both are same
return index+1;
}
return search(value,index++);
}
何らかの理由でStackOverflowError
が表示されているようです。
'++ index'を使うべきですか? – Nishant
templatetypedefで正しく識別されたエラーを修正したとしても、リスト内の要素ごとにスタックフレームを使用しているという問題がありますので、リストが数千の要素。リストがどのようにソートされているかを見ると、代わりにバイナリ検索を実装したいと思うでしょう。 – Dolda2000