2017-02-12 31 views
0

嗨,我已经被授权编写一个简单的程序,给定一个整数数组并确定模式,这是数组中最常出现的数字。使用bin搜索寻找一个排序数组的模式

我试图采用的方法是使用泡沫排序与斌搜索算法我的知识水平是在初学者阶段可以有人帮助指向我吗?

我在哪里出错我相信它是通过正确的搜索值在数组中找到它!但我可能错了,但一些帮助将非常感谢,提前感谢那些需要时间来尝试帮助我。

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

您可以通过'的std :: sort'取代你的布雷排序。 – Jarod42

+0

没有什么可搜索的。计算排序数组中每个重复数字序列的长度,然后查找最长的序列。 – felix

+0

我有倾向于过度复杂的问题/任务认为这可以用更简单/更简单的方式解决 – Cerberus

回答

0

您不需要对数组进行排序。你可以有另外一个数组(freq),它会统计出现的数字。所以,对于一个小型代码:

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

我希望你有这个想法:)

+0

谢谢,但我不是100%确定你的代码中发生了什么。我认为我可以按照但不是100%确定,因为我在我的知识初学者水平之前躲过了 – Cerberus

+0

在这段代码中,您只需计算每个元素的出现次数,然后从该次出现中选择最大值。 –

相关问题