0
我最近完成了我的代碼,但我的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;
}
歡迎堆棧溢出。當你編寫代碼時,儘可能地單獨開發新的功能非常重要。在這種情況下,在嘗試將其掛接到執行諸如搜索和用戶I/O之類的大型程序之前,應該使氣泡排序完美工作(使用'printArray()'進行診斷)。 – Beta
哈哈謝謝。但是,我不太清楚如何修復bubbleSort函數。 @Beta –
我投票結束這個問題作爲題外話題,因爲它涉及與問題標題無關的一個簡單和常見的錯誤。這個問題不太可能對未來的讀者有所幫助。 – Beta