搜索时出现逻辑错误

时间:2016-07-31 21:00:03

标签: c++

我最近完成了我的代码,但我的bubbleSort函数输出错误。 我错过了前两个元素。

我试图改变一下,但仍然没有成功。

NUM_FOR_CAL1

NUM_FOR_CAL2

似乎是我的问题。

任何人对如何解决此逻辑错误有任何想法?

 //Searching Benchmarks exercise
#include <iostream>
#include <stdlib.h>

using namespace std;

//module prototypes
int binarySearch(int t, int arr[], int n);
int bubbleSort(int num[], int n);
void printArray(int arr[], int SIZE);


//global constants
const int SIZE=20;
const int NUM_FOR_CAL1=1;
const int NUM_FOR_CAL2=2;
const int ZERO_FOR_CAL=0;

int main()
{
    //some variables
   int swap;
   int arr[SIZE] = {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51};

   //Showing original order, bubble sort, and the number of swaps
   cout << "Original Order : ";
   printArray(arr, SIZE);
   swap = bubbleSort(arr, SIZE);
   cout << "Bubble Sorted : ";
   printArray(arr, SIZE);
   cout << "Number of location swaps: " << swap << endl;
   int num, pos, total = ZERO_FOR_CAL;
   char YesNo;
   do
   {
      cout << "Select a number in the Array to search for: ";
      cin >> num;
      pos = binarySearch(num, arr, SIZE);
      cout << "Sequential Search comparisons: " << pos + NUM_FOR_CAL1<< endl;
      cout << "The position of the number is " << pos + NUM_FOR_CAL1 << endl;
      if(pos != -NUM_FOR_CAL1) total++;
      cout << "Binary Search comparisons: " << total << endl;
      cout << "The position of the number is " << pos + NUM_FOR_CAL1 << endl;
      cout << "Do you want to search again (Y = Yes) : ";
      YesNo = NUM_FOR_CAL2;
      cin >> YesNo;
   }//end of do while loop to search for array and display comparisons
    while(YesNo == 'Y' || YesNo == 'y');

   system("Pause");
   return 0;
}//end main

//searching array using binarySearch
int binarySearch(int t, int arr[], int n)

{
   for(int i = ZERO_FOR_CAL; i < n; ++i)
     if(arr[i] == t) return i;
   return -NUM_FOR_CAL1;
}//end of binarySearch

//searching array using bubbleSort
int bubbleSort(int num[], int n)
{
int i, j, flag = NUM_FOR_CAL1;
int temp, swap = ZERO_FOR_CAL;

for(i = NUM_FOR_CAL1; (i <= n) && flag; i++)
{
    flag = NUM_FOR_CAL2;
    for (j = NUM_FOR_CAL2; j < (n-NUM_FOR_CAL1); j++)
    {
        if (num[j+NUM_FOR_CAL1] < num[j])
        {
            temp = num[j];
            num[j] = num[j+NUM_FOR_CAL1];
            num[j+NUM_FOR_CAL1] = temp;
            flag = NUM_FOR_CAL1;
            swap++;
        }//end of if statement
    }//end of for loop
}//end of for loop
return swap;
}//end bubbleSort

void printArray(int arr[], int SIZE)
{

   for(int i = 0; i < SIZE; i++)
   {
      cout << arr[i];
      if(i < SIZE - 1) cout << ", ";
   }
   cout << endl;
}

1 个答案:

答案 0 :(得分:1)

您的Updated 1 record(s) in 22ms循环:

j

从j = 2开始,因此它根本不会查看数组的前两个元素。

检测此问题的一种好方法是从较小的数组开始并使用诊断输出语句,如:

for (j = NUM_FOR_CAL2; ... )