2016-08-05 72 views
0

問題:給定一個數組(ArrayInts)計算所有偶數整數和奇數整數的和,然後搜索數組中所有奇數整數之和的目標值使用二進制搜索。如果在數組中找到目標值,則顯示找到目標值的數組索引,否則顯示目標未找到。C++中的二進制搜索排序和索引

我沒有得到正確答案。我不相信正在讀取我想讀取的數組。當我編譯時,我得到數組是{6487456},偶數的總和是678,二叉搜索沒有找到賠率549和目標。這是我現在的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 


double ArrayInts[]={54,152,99,-8,3,19,-11,260,27,-4,10,12,15,58,480,60}; 
int Bin_Search(double ArrayInts[],int low, int high, double target); 

int main(void) 
{ 
int i,j,n=16,sum_even,sum_odd, index,len; 
double ArrayInts[16]={54,152,99,-8,3,19,-11,260,27,-4,10,12,15,58,480,60}, target; 

//Implemeting Bubble sort 
for(i=0;i<n-1;i++) 
    for(j=0;j<n-1;j++) 
    { 
     if (ArrayInts[j]>ArrayInts[j+1]) 
     { 
      len=ArrayInts[j]; 
      ArrayInts[j]=ArrayInts[j+1]; 
      ArrayInts[j+1]=len; 
     } 
    } 

//Function call to add even and odd numbers from array 
for(i=0;i<16;i++) 
{ 
    if(i%2==0) 
    sum_even+=ArrayInts[i]; 

    else 
    sum_odd+=ArrayInts[i]; 
} 

printf("The array is {%d}\n",ArrayInts); 
printf("The sum of all even numbers in the array is: %d\n",sum_even); 
printf("The sum of all odd numbers in the array is: %d\n",sum_odd); 

//Function call to search for target value 
index = Bin_Search(ArrayInts,0,15,target); 

if(index != -1) 
printf("Target found at index %d\n", index); 
else 
printf("Target was not found\n"); 

system("pause"); 
return (0); 
} 

int Bin_Search(double ArrayInts[],int low, int high, double target) 
{ 
int mid; 

if (low>high) 
    return -1; 

mid=(low+high)/2; 
if(ArrayInts[mid]==target) 
    return(mid); 

else if (ArrayInts[mid]<target) 
    return Bin_Search(ArrayInts, mid+1, high, target); 
else 
    return Bin_Search(ArrayInts, low, mid-1, target);  
} 
+0

你要我們來回答你貼有一個更好的C++實現的問題,或嘗試修復你的代碼?順便說一下,這是一個使用C++算法的4或5行程序。 – PaulMcKenzie

+0

你已經聲明瞭同名的全局和局部變量,你的局部變量總是要在程序中讀取。使用適當的命名約定。 –

+0

我想要用目前正在完成的方式修復/向我解釋代碼。我從其他一些海報中看到代碼應該是多麼簡短,但是,這超出了我正在學習的課程的範圍,所以與我的教授不太一致 – mripkiss94

回答

1

sum_even未初始化。

sum_odd未初始化。

target未初始化。

這些變量都沒有初始化。因此,這會導致未定義的行爲。

鑑於這涉嫌c++,使用std::sort排序您的數組,而不是編碼自己的排序。如果這確實是C,請改爲使用qsort(3)

0

隨着range/V3,這將是:

std::vector<int> v = {54,152,99,-8,3,19,-11,260,27,-4,10,12,15,58,480,60, 480-163}; 
auto is_even = [](int i) {return i % 2 == 0;}; 
auto is_odd = [](int i) {return i % 2 == 1;}; 

const auto even_sum = ranges::v3::accumulate(v | ranges::v3::view::filter(is_even), 0); 
const auto odd_sum = ranges::v3::accumulate(v | ranges::v3::view::filter(is_odd), 0); 
ranges::v3::sort(v); 
const auto target = 27; 
auto found = ranges::v3::binary_search(v, target); 

std::cout << "The sum of all even numbers in the array is:" << even_sum << std::endl; 
std::cout << "The sum of all odd numbers in the array is:" << odd_sum << std::endl; 
std::cout << target << (found ? " Found" : " Not found") << std::endl; 

Demo