冒泡排序后BinSearch失败

时间:2014-04-10 02:54:25

标签: c++ sorting

我的节目似乎突然表现得很奇怪,无论我怎么看,我都无法弄明白为什么。

让我们从标题

开始
    //inventoryData.h
//This is the second edition of inventory data, now featuring an actual description
//This header will load an array, sort it, and then be used in InventorySearch to produce parts and prices.
//by Robert Moore on [DATE]

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

class InventoryData{
    //Variables
    private:
        int partNum[1000];
        double price[1000];
        int invCount;

    public:
        InventoryData();//Build Up
        void loadArrays(); //Feed the data from the database into our arrays
        void arraySort(); //Bubblesort for the array
        int seqSearch(int); //Our one by one search method
        int binSearch(int); //The other search
        int returnpart(int); //Return Part Number
        double returnPrice(int); //Return price

        //Incorportate a search counter to both these searches?
                //IE: bin search found [x] (completed after [y] records)

};

InventoryData::InventoryData()
{
    //Load the array
    invCount = 0;
    for (int count = 0; count < 1000; count++)
    {
        partNum[count] = 0;
        price[count] = 0;
    }
}

void InventoryData::arraySort()
{
    int counter = 0; //Used to keep track of subscripts
    int temp = 0; //Used to sort subscript contents
    double tempPrice = 0;
    int maxSub = invCount; 
    int lastKnown  = 0; //Used to indicate what the last swapped value was
    char swap = 'Y'; //used to indicate if a swap was made or not

    while (swap == 'Y')
    {
        swap = 'N';
        counter = 0;


        while (counter < maxSub){
            if (partNum[counter] < partNum[counter+1])
            {

                //Swap the part number
                temp = partNum[counter];
                partNum[counter] = partNum[counter+1];
                partNum[counter+1] = temp;

                //Swap the price
                tempPrice = price[counter];
                price[counter] = price[counter+1];
                price[counter+1] = tempPrice;

                //Report the swap occured
                swap = 'Y';
                lastKnown = counter;
            }
            counter++;
            }//End of While Loop
            maxSub = lastKnown;
        }//End this While Loop Too
    cout<<"File sort complete."<<endl;
}

void InventoryData::loadArrays()
    {
        ifstream partIn;
        partIn.open("masterInventory.dat");
        cout<<"Loading..."<<endl;
        if (partIn.is_open())
            {
                //Prime Read
                partIn    >>    partNum[invCount]
                          >>    price[invCount];

                //cout<<partNum[invCount]<<" and "<<price[invCount] <<" have been loaded."<<endl;            

            while(!partIn.eof())
                {
                                invCount++;
                    partIn  >>  partNum[invCount]
                            >>  price[invCount];
            //  cout<<partNum[invCount]<<" and "<<price[invCount] <<" have been loaded."<<endl; 

                } //END While

            partIn.close();
            cout<<"All files loaded successfully."<<endl;
            }   //END IF*/

        else
            {
                invCount = -1;
                cout<<"File failed to open."<<endl;
            }
            //arraySort();
    }



int InventoryData::seqSearch(int searchKey)
{
    int index = 0;
    int found = -1;
    int counter = 0;
    while(index < invCount)
    {
        counter++;
        if (searchKey == partNum[index]
)
        {
            found = index;
            index = invCount;
        }
        else
        {
            index++;
        }

    }
    cout<<"(Sequential completed after reading "<< counter<<" files.)"<<endl;
    return found;

}

int InventoryData::binSearch(int searchKey)
{
    int first = 0;
    int last = invCount;
    int found = 0;
    int mid = 0;
    int counter = 0;

    while (first <= last && found == 0)
    {
        counter++;
        mid = (first + last)/2;
        if (searchKey == partNum[mid] ){
            found = 1;

            return mid;
        }
        else
        {
            if (partNum[mid] < searchKey)
            {
                first = mid+1;
            }
            else 
            {
                last = mid - 1;
            }

        }
    }
    if (found == 0)
    {
        mid  = -1;

    }
    cout<<"(Binary completed after reading "<< counter <<" files.)"<<endl;
    return mid;
}

int InventoryData::returnpart(int value)
    {
        return partNum[value];
    }

double InventoryData::returnPrice(int value)
    {
        setprecision(2);
        return price[value];
    }

通过这个设置,程序从数据库加载数字(任意数字的随机组合和另一组“价格”),然后我们调用函数来加载,排序和搜索数组,如CPP中所示文件

//InventorySearch
/*This file is used to search our databases
and return a value for whatever our search may
be looking for.*/
//by Robert Moore


#include "inventoryData.h"
#include <iomanip>
int main()
{
    //Declare Variable
    int tempSeq = 0;
    int tempBin = 0;
    int search = 0;
    char confirmation = 'Y';
    int searchCounter = 0;
    int partsFound = 0;
    int partsLost = 0;

    //Build Object and Load Array
    InventoryData invent;
    invent.loadArrays();
    invent.arraySort();

    //Introduction
    cout<<"Welcome to Part Search."<<endl;

//Begin Loop Here
    while(confirmation != 'N')
    {

        cout<<"Please enter a part number: ";
        searchCounter++;
        cin>>search;
        cout<<endl;


        tempSeq = invent.seqSearch(search);
        if (tempSeq != -1)
        {
              std::cout << std::fixed;
            cout<<"Sequential found part number "<<invent.returnpart(tempSeq)<< ", and it's price is "<<setprecision(2)<<invent.returnPrice(tempSeq)<<endl;
            partsFound++;
        }
        else
        {
            cout<<"Sequential search failed to find part number "<<search<<endl;
            partsLost++;
        }

        tempBin = invent.binSearch(search);
    if (tempBin != -1)
        {
            std::cout << std::fixed;
            cout<<"Binary found part number "<<invent.returnpart(tempBin)<<", and it's price is "<<setprecision(2)<<invent.returnPrice(tempBin)<<endl;
            partsFound++;
        }

    else
        {
            cout<<"Binary search failed to find part number "<<search<<endl;
            partsLost++;
        }
        cout<<"Would you like to search again? (Plese enter Y/N): ";
        cin>>confirmation;
        confirmation = toupper(confirmation);
        }

    cout<<"Today's Summary: "<<endl;
    cout<<setw(5)<<"Total searches: "<<setw(25)<<searchCounter<<endl;
    cout<<setw(5)<<"Total successful searches:"<<setw(15)<<(partsFound/2)<<endl;
    cout<<setw(5)<<"Total unsuccessful searches:"<<setw(12)<<(partsLost/2)<<endl;

    cout<<"Thank you for using Part Search. Have a nice day."<<endl;
    return 0;
}

但是,输出会遇到以下问题:顺序搜索将搜索整个数据库并找到我们的值,binSearch最多只能搜索8个值并失败。起初我以为这是由于排序的加载方式,但是一旦我编码出来,它就会继续失败。更糟糕的是,除了添加排序之外,程序功能在此之前就好了。

关于程序错误的地方,我的想法已经不多了,因为这段代码在添加arraySort()之前就已经很好了。

2 个答案:

答案 0 :(得分:1)

arraySort()方法中,您应该注意以下事实:例如maxSub=10,然后是您编写的部分

 while (counter < maxSub){
        if (partNum[counter] < partNum[counter+1])
        {
         .....
        }
 }

你最终可能会执行

 if(partNum[9]<partNum[10]){
  ....
 }

由于C ++不对数组执行绑定检查,因此您的代码虽然有缺陷,但最终可能会成功编译,并且可能(或可能不会)生成正确的结果。因此,您需要将循环条件更改为

  while((counter+1)<maxSub){
     .....
  }

此外,您的arraySort()按降序排序,而binSearch()已针对按升序排序的数组实施。您可以根据自己的要求更改其中一种方法。

希望这有帮助。

答案 1 :(得分:0)

你的排序算法对我来说似乎有问题。如果您正在尝试冒泡排序,排序实现应该是这样的。

for(int counter1 = 0;counter1<invCount; ++counter1)
{
    for(int counter2 = counter1+1; counter2<invCount; ++counter2)
    {
        if(partNum[counter1] < partNum[counter2])
        {
             //do swaping here.
        }
    }
}