2011-04-18 47 views
0

我忘了插入我的代碼,對不起,我代表我..二進制代碼錯誤幫助

我有一個二進制搜索我的程序中去,但是當我輸入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 
} 
+1

我試着把它清理一下,但該死的是一些非常難看的代碼.- – Blindy 2011-04-18 23:27:43

+0

數組的定義在哪裏?如果它有'N_STUDENT'元素,則搜索並排序爲'N_STUDENT'而不是'N_STUDENT-1'以包含最後一個元素。 – AJG85 2011-04-18 23:32:48

+0

取決於什麼'merge_sort'確實,但是,他的二進制搜索功能確實如此。 – Blindy 2011-04-18 23:34:07

回答

1

簡單,你upto實際上是一個獨特的結合,所以將其替換您的6號線:

k=binarySearch(record, 0, N_STUDENT, key); // Serach Array 

一般而言,複製代碼,而不理解它是做功課好辦法。當StackOverflow用戶忽略可怕的貼圖時,時間將會到來,您將無法完成它。

+0

我看到了我在大學給出的網站上的代碼。這給你示例代碼,所以我看到了,我編輯,以適應我的需要。 -1強制排序如果排序不完成,所以允許二進制搜索工作。 – David 2011-04-19 07:12:08