二进制码错误帮助

Binary code Error help

本文关键字:帮助 错误 二进制      更新时间:2023-10-16

我忘记插入我的代码了,对不起。

我的程序中有一个二进制搜索,但是当我在数组中输入10个学生记录并对它们进行排序时,student ID的最后一个元素将不会从我的二进制搜索中拾取。

说当我排序数组和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<<" nt 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 Numbern "  <<key<<  "exists at the position n"  << k
                << " Student Numbern" << 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
}

很容易,你的upto实际上是一个排他的边界,所以将你的第6行替换为:

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

一般来说,在不理解代码的情况下复制代码是一种糟糕的做功课的方式。总有一天,你的粘贴会被StackOverflow用户忽略,你将无法完成它。