我忘了插入我的代碼,對不起,我代表我..二進制代碼錯誤幫助
我有一個二進制搜索我的程序中去,但是當我輸入10個學生記錄到一個數組和排序,最後學生證的元素不會從我的二分查找中找到。
說我排序數組和232是陣列中的最後一個元素時,當我去搜索232二進制搜索功能給我找不到,我尋找數組中的任何其他ID並將其返回與記錄。
else if (choice == 4) // Binary Search... This Also Force Array to be Sorted If Array is not Sorted.
{
merge_sort(0,N_STUDENT-1);
cout<<" \n\t Enter the student number to search :"; // Ask user to Input Student ID.
cin>>key;
k=binarySearch(record, 0, N_STUDENT-1, key); // Serach Array
if(k>=0)
cout<<"Student Details with student Number\n " <<key<< "exists at the position \n" << k
<< " Student Number\n" << record->student_number << " " << " Student Name \n" << record->studentname << " " << " Student Address \n" << record->Address << " " << " Course Code \n" << record->CourseCode << " " << " Course Name \n" << record->CourseName; //Displays Position of Student And Student Details.
else
cout<< "Not found "; // if Record is not Found
_____________________________________________________________________________________________________
//function binary search using the key value to serach
int binarySearch(student sorted[], int first, int upto, int key) { // Sort Array if not Sorted...
while (first < upto) {
int mid = (first + upto)/2; // Compute mid point.
if (key<sorted[mid].student_number)
{
upto = mid; // repeat search in bottom half.
} else if (key>sorted[mid].student_number)
{
first = mid + 1; // Repeat search in top half.
} else
{
return mid; // Found it. return position
}
}
return -(first + 1); // Failed to find key
}
我試着把它清理一下,但該死的是一些非常難看的代碼.- – Blindy 2011-04-18 23:27:43
數組的定義在哪裏?如果它有'N_STUDENT'元素,則搜索並排序爲'N_STUDENT'而不是'N_STUDENT-1'以包含最後一個元素。 – AJG85 2011-04-18 23:32:48
取決於什麼'merge_sort'確實,但是,他的二進制搜索功能確實如此。 – Blindy 2011-04-18 23:34:07