使用 bin 搜索查找排序数组的模式

Finding the mode of a sorted array using bin search

本文关键字:数组 模式 排序 查找 bin 搜索 使用      更新时间:2023-10-16

嗨,我的任务是编写一个简单的程序,该程序给定一个整数数组并确定模式,这是数组中出现频率最高的数字。

尝试采用的方法是使用带有垃圾箱搜索算法的气泡排序,我的知识水平处于初学者阶段,有人可以帮我指出吗?

我出错的地方我相信它传递了正确的搜索值以在数组中找到它!但我可能错了,但一些帮助将不胜感激,提前感谢那些花时间帮助我的人。

#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;
}

我希望你明白:)