C++中的二进制搜索排序和索引
Binary Search sorting and indexing in C++
问题:给定一个数组(ArrayInts(,计算所有偶数整数和奇数整数的和,并使用二进制搜索在数组中搜索所有奇数整数和的目标值。如果在数组中找到目标值,则显示找到目标值的数组索引,否则显示未找到目标
我没有得到正确的答案。我不相信我想被读取的数组正在被读取。当我编译时,我得到数组是{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: %dn",sum_even);
printf("The sum of all odd numbers in the array is: %dn",sum_odd);
//Function call to search for target value
index = Bin_Search(ArrayInts,0,15,target);
if(index != -1)
printf("Target found at index %dn", index);
else
printf("Target was not foundn");
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);
}
sum_even
未初始化。
sum_odd
未初始化。
target
未初始化。
这些变量均未初始化。因此,这会导致未定义的行为。
假设这是所谓的c++
,请使用std::sort
对数组进行排序,而不是编写自己的排序。如果这真的是C
,请使用qsort(3(。
对于范围/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;
演示
相关文章:
- 如何根据排序索引的向量对 std::index 集进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 排序谓词没有传递对索引对象的引用?
- 如何在对向量排序后更改索引值?c++
- 在不进行排序的情况下查找数组中n个最小值的索引
- 如何解决索引和排序问题
- 使用C++中的排序对索引进行排序
- 如何使equal_range迭代器在 Boost 多索引中按不同的索引排序?
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 根据某些条件对索引子集进行排序
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- 如何对同一数组索引下的结构成员进行排序?
- 如何在保留原始索引的同时对向量的向量进行排序
- 如何获取向量的排序索引
- 基于其他信息的C 排序索引
- 如何将未排序数组的排序索引放入新数组中
- boost多索引排序索引中插入的匹配函数
- c++就地排序索引文件(使用堆排序)
- C++快速排序索引0返回-842150451
- 快速排序索引问题