gpt4 book ai didi

c++ - 搜索逻辑错误

转载 作者:行者123 更新时间:2023-11-28 05:34:17 24 4
gpt4 key购买 nike

我最近完成了我的代码,但是我的 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;
}

最佳答案

你的 j 循环:

for (j = NUM_FOR_CAL2; ... )

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

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

cout << "now comparing " << num[j+1] << " to " << num[j] << endl;

关于c++ - 搜索逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38688362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com