使用 bin 搜索查找排序数组的模式
Finding the mode of a sorted array using bin search
嗨,我的任务是编写一个简单的程序,该程序给定一个整数数组并确定模式,这是数组中出现频率最高的数字。
我尝试采用的方法是使用带有垃圾箱搜索算法的气泡排序,我的知识水平处于初学者阶段,有人可以帮我指出吗?
我出错的地方我相信它传递了正确的搜索值以在数组中找到它!但我可能错了,但一些帮助将不胜感激,提前感谢那些花时间帮助我的人。
#include <iostream>
using namespace std;
const int arrayLength = 10;
int searchVal;
int numGroup[arrayLength];
bool isSorted(int [], int arrayLength);
int binSearch(int [],int arrayLegth,int searchVal);
int main()
{
// Take in num
for (int index = 0; index < arrayLength; index++)
{
cout << "Enter Number: ";
cin >> numGroup[index];
}
// Sort numbers
//var to hold the val being swaped
int swapHolder = 0;
//bubble sort
for (int iSort = 0; iSort < arrayLength; iSort++)
{
for (int jSort = (iSort + 1); jSort <= arrayLength - 1; jSort++)
{
if (numGroup[iSort] > numGroup[jSort])
{
swapHolder = numGroup[iSort];
numGroup[iSort] = numGroup[jSort];
numGroup[jSort] = swapHolder;
}
}
}
//passes the sorted array and the length to the isSorted
isSorted(numGroup, arrayLength);
return 0;
}
bool isSorted(int numGroup[], int arrayLength){
cout << "Final result" << endl;
for (int index = 0; index < arrayLength - 1 ; index++)
{
if (numGroup[index] > numGroup[index + 1])
{
cout << "it's false";
system("pause");
return false;
}
cout << numGroup[index] << endl;
//cout << arrayLength << endl;
}
cout << numGroup[arrayLength - 1] << endl;
//trying to make searchVal
for (int i = 0; i < numGroup[arrayLength - 1]; i++)
{
if (numGroup[i] == numGroup[i])
{
int searchVal = numGroup[i];
}
}
binSearch(numGroup, arrayLength, searchVal);
cout << "It's true ";
system("pause");
return true;
}
int binSearch(int numGroup[], int arrayLength,int searchVal){
int low = 0;
int high = arrayLength - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
//search through the array
if (searchVal == numGroup[mid])
{
return mid;
}
else if (searchVal > numGroup[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "In bin search " << mid;
return mid;
}
您不需要对数组进行排序。您可以有另一个数组(频率(来计算出现的数字。因此,一个迷你代码:
int myArray[10];
int freq[1000]; //we assume that the numbers are smaller than 1000
void count()
{
for(int i = 0; i < 10; ++i)
{
++freq[v[i]];
}
}
int ReturnModeElement()
{
int maxFreq = -1;
int element = -1;
for(int i = 0 ; i < 10; ++i)
{
if(freq[v[i]] > maxFreq)
{
maxFreq = freq[v[i]];
element = v[i];
}
}
return element;
}
我希望你明白:)
相关文章:
- C++ 无法在字符数组中使用 for 循环打印字母模式
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在数组中查找重复模式
- 如何在 2D 数组中编写此模式?
- 在数组中查找模式的最有效方法?
- 如何以模式获取数组中的数据?
- 从列表到数组C 查找模式或最常见的数字
- 查找未排序数组的模式,以及该数组是否具有多个模式或无模式
- 如何通过将数组的指针传递给函数来查找数组的模式?C++
- 在数组中查找一个或多个模式
- 为什么使用char数组来存储以二进制模式打开的文件的内容
- 正在初始化带模式的“constexpr”数组
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- 无模式例外是什么意思?(数组中出现次数最多的数字)
- 在调试模式下释放静态数组时出错
- 在多线程代码中缓存友好的数组迭代模式
- 如何以特定模式对字符串数组进行排序
- 在函数搜索模式中引用二维数组时出错
- 如何在字节数组中搜索模式
- 数组类型具有用于模式匹配的不完整元素类型