I am stuck and a simple yet crazy search algorithm. I want to find the index of an element from an array calling a function. The problem is that although the element is already there, the function returns -1; which is supposed to return only if the element is not there.
This is the code:
#include <iostream>
using namespace std;
int search(int arr[], int size, int val, bool left) {
int res;
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
else if(val != arr[i]) {
res = -1;
}
}
return -1;
}
int main() {
int arr[] = {1, 4, 6, 5, 2, 7, 10, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << search(arr,size,6, true) << endl;
return 0;
}
Thanks in advance.
Try Return res from the function
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int search(int arr[], int size, int val, bool left) {
int res = -1;
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
}
return res;
}
int main() {
int arr[] = {1, 4, 6, 5, 2, 7, 10, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << search(arr,size,6, true) << endl;
return 0;
}
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
else if(val != arr[i]) {
res = -1;
}
}
return -1;
You are returning -1 outside of for loop even when the element is present.
Initialize res variable above for loop and return it
res = -1
After for loop
return res
Related
bool isSubset(int arr1[], int m,int arr2[], int n){
set<int> hashset;
for (int i = 0; i < m; i++){
hashset.insert(arr1[i]);
}
for (int i = 0; i < n; i++) {
if (hashset.find(arr2[i]) == hashset.end())
return false;
}
return true;
}
Is this correct method to find whether arr2 is sub array of arr1 or not
because sub array is contiguous part of array but this code is not checking for any order that's why I want to be sure.
Is this correct method to find whether arr2 is sub array of arr1 or not
No, it isn't. Your method doesn't consider the order of elements. It is more of a method to find whether a bunch of numbers (given in arr2) exist in an arr1.
For instance, if int arr1[] = {1, 2, 3} and int arr2[] = {2, 1}, the method you implemented will return true, while it should return false.
Here is how you would do it:
#include <iostream>
bool isSubset(int array[], int m, int subarray[], int n)
{
if (n > m)
return false;
for (int i = 0; i <= m-n; i++) {
int ii = i, j;
for (j = 0; j < n; j++)
if (subarray[j] != array[ii])
break;
else
ii++;
if (j == n)
return true;
}
return false;
}
Then call it like this:
int main()
{
int array[] = {1, 2, 3};
const int m = sizeof(array) / sizeof(*array);
int subarray1[] = {1, 2};
const int n1 = sizeof(subarray1) / sizeof(*subarray1);
int subarray2[] = {2, 1};
const int n2 = sizeof(subarray2) / sizeof(*subarray2);
std::cout << isSubset(array, m, subarray1, n1) << "\n"; // Will print 1
std::cout << isSubset(array, m, subarray2, n1) << "\n"; // Will print 0
}
You understood that the way your code is checking subarray is wrong.
A suggestion-
Use of C language style array in C++ is discouraged. Instead, you should use the appropriate standard container, provided in Containers library. You can use std::array container in place of plain C style array. Below is the sample code to check subarray:
#include <iostream>
#include <array>
#include <algorithm>
int main () {
std::array<int,12> arr1 {9,5,2,5,9,2,4,7,0,4,5,1};
std::array<int,3> arr2 {5,9,2};
bool res = false;
size_t pos = 0;
std::array<int,12>::iterator x;
while ((x = std::find(arr1.begin() + pos, arr1.end(), arr2[0])) != arr1.end()) {
size_t currpos = x - arr1.begin();
if ((arr1.size() - currpos >= arr2.size()) &&
((std::equal(arr1.begin() + currpos, arr1.begin() + currpos + arr2.size(), arr2.begin())))) {
res = true;
break;
}
pos = currpos + 1;
}
if (res) {
std::cout << "arr2 is subarray of arr1" << std::endl;
} else {
std::cout << "arr2 is not subarray of arr1" << std::endl;
}
return 0;
}
I need help trying to find the min and max values in an array recursively in c++. the functions were given and cannot be changed.
I tried it out for both but for some reason nothing happens and the code does not enter the loop and I want to know what I am doing wrong. Here is my main and the min and max functions.
int main()
{
int array[] = { 46, 22, 7, 58, 91, 55, 31, 84, 12, 78 };
if (findMax(array, 10) == 91)
{
cout << "findMax is correct!" << endl;
}
if (findMin(array, 10) == 7)
{
cout << "findMin is correct!" << endl;
}
int findMax(int array[], int size)
{
int i = (size - 1);
int max = 0;
if (array[0] < array[i]) {
max = array[i];
findMax(array, size - 1);
}
return max;
return 0;
}
int findMin(int array[], int size)
{
int i = 0;
int j = size - 1;
if (i == j)
{
return array[i];
i++;
}
int temp = findMin(array, size);
if (array[i] < temp)
{
return array[i];
}
else
{
return temp;
}
}
}
Well, you simply go backwards, return the min of each pair of elements and then next level make array size one smaller. Example:
int findMin(int array[], int n)
{
// if size = 0 means whole array has been traversed
if (n == 1){
return array[0];
}
return min(array[n-1], findMin(array, n-1));
}
And you can do the findMax using the same methodology.
I'm trying to write a function that calculates the sum of an array, but when i declare int size = 0; , the function runs 0 times because i=0 ; i
int arraChec(int arra[]) {
int size = 0;
int sum = 0;
for (int i = 0; i < size; i++) {
sum = sum + arra[i];
}
return sum;
}
int main() {
int arra1[7] = { 2,3,5,7,8,9,1 };
cout << arraChec(arra1) << endl;
system("pause");
}
Pass in the array size as a parameter:
#include <iostream>
int arraChec(int arra[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arra[i];
}
return sum;
}
int main() {
int arra1[7] = { 2, 3, 5, 7, 8, 9, 1 };
std::cout << arraChec(arra1, 7) << std::endl;
}
Or use std::vector:
#include <iostream>
#include <vector>
int arraChec(std::vector<int>& arra) {
int sum = 0;
for (int i = 0; i < arra.size(); i++) {
sum += arra[i];
}
return sum;
}
int main() {
std::vector<int> arra1 = { 2, 3, 5, 7, 8, 9, 1 };
std::cout << arraChec(arra1) << std::endl;
}
If you are referring to some C style (sizeof(arra) / sizeof(*arra)) construct I suggest you refrain from using it.
You need to pass two arguments to the function--either the beginning of the array plus the size, or the beginning and (one past the) end, as is conventional in C++:
int arraChec(int* begin, int* end) {
int sum = 0;
for (int* it = begin; it < end; ++it) {
sum += *it;
}
return sum;
}
int main() {
int arra1[7] = { 2,3,5,7,8,9,1 };
cout << arraChec(std::begin(arra1), std::end(arra1)) << endl;
system("pause");
}
Of course, you can implement is using the standard library:
cout << std::accumulate(std::begin(arra1), std::end(arra1), 0) << endl;
Use std::array instead of fixed size C-style array.
#include <iostream>
#include <array>
#include <numeric>
using namespace std;
int main() {
array<int, 7> arr = { 2, 3, 5, 7, 8, 9, 1 };
cout << accumulate(arr.begin(), arr.end(), 0) << endl;
return 0;
}
Output
35
Read more about std::accumulate.
Another way not mentioned yet is:
template<size_t N>
int arraChec(int (&arra)[N]) {
int sum = 0;
for (size_t i = 0; i < N; i++) {
sum = sum + arra[i];
}
return sum;
}
I am doing the program in which i am checking that if the array is balance or not like the array
int a5[] = {2, 1, 4, 3}; // balance array because i got even number on even position so program return 1
int a5[] = {3, 1, 4, 3}; // un balance array because i got odd number on even position so program return 0
This is my program which i am trying
int araay(int arg[], int length);
int main()
{
int a6[] = {3, 3, 4, 4};
int a7[] = {2, 2, 3, 4};
int a8[] = {4, 1, 2, 3};
int a9[] = {1, 1};
araay (a7,sizeof(a7));
}
int araay (int arg[], int length)
{
int sumEven = 0;
int sumOdd = 0;
for (int i=0; i<=length; i=i+2)
{
if (arg[i]%2 == 0)
{
sumEven++;
}
else
sumOdd++;
}
for (int i=1; i<=length; i=i+2)
{
if (arg[i]%2 == 0)
{
sumEven++;
}
else
sumOdd++;
}
return 0;
}
in return it always return me 00000 something like zero everytime
Following may help: (http://ideone.com/NttqbY)
bool is_balanced(const std::vector<std::size_t>& v)
{
for (std::size_t i = 0; i != v.size(); ++i) {
if ((i % 2) != (v[i] % 2)) {
return false;
}
}
return true;
}
Thanks all for your comments and help
This is what i tried
int araay(int arg[], int length);
int main()
{
int a6[] = {3, 3, 4, 4};
int a7[] = {2, 3, 2, 3};
int a8[] = {4, 1, 2, 3};
int a9[] = {1, 1};
araay (a7,3);
}
int araay (int arg[], int length)
{
int sumEven = 0;
int sumOdd = 0;
for (int i=0; i<=length; i+=2)
{
if (arg[i]%2 != 0)
{
cout<<"unbalanced"<<endl;
// return 0;
}
else
{
sumEven++;
}
}
for (int i=1; i<=length; i=i+2)
{
if (arg[i]%2 == 0)
{
cout<<"unbalanced"<<endl;
sumEven++;
}
else
{
sumOdd++;
// return 0;
}
}
return 0;
}
but the answer of #jarod is looking more suitable and easy
This is what you can do
#include <iostream>
int check(int arg[])
{
for (auto i = 0; i < sizeof(arg); ++i)
{
if ((i % 2) != (arg[i] % 2))
{
return 0;
}
}
return 1;
}
void main()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 2, 3, 4, 5 };
int c[] = { 2, 2, 3, 3 };
std::cout << "a = " << check(a) << std::endl;
std::cout << "b = " << check(b) << std::endl;
std::cout << "c = " << check(c) << std::endl;
getchar();
}
How do I sort an array without using a loop in C++? I think it might use recursion, but I do not know how to implement it.
Use std::sort defined in algorithm header file
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[]={5,3,4,1,2};
sort(a,a+5);
for(int i=0;i<5;i++)
cout<<a[i]<<" "; // 1 2 3 4 5
return 0;
}
//C++
void bubblesort(vector<int> &arr, int iteration) {
if(iteration == 0)
return;
bubbleswap(arr, 0, 1, iteration);
bubblesort(arr, iteration-1);
}
void bubbleswap(vector<int> &arr, int i, int j, int n) {
if(j>=n)
return ;
if(arr[i] < arr[j]){
swap(arr[i], arr[j]);
}
bubbleswap(arr, i+1, j+1, n);
}
void sort(vector<int> &arr) {
int n = arr.size();
if(n<=1)
return ;
bubblesort(arr, n);
}
Recursive Selection Sort
#include <iostream>
#include <vector>
using namespace std;
//----------------------------------------------------------
int recursive_min(vector<int>& a, size_t first) {
//base case
if (first + 1 >= a.size()) {
return first;
}
else {
size_t min_index {first};
int temp_index {recursive_min(a, first + 1)};
if (a[min_index] > a[temp_index]) {
min_index = temp_index;
}
return min_index;
}
}
//----------------------------------------------------------
void selectionSort(vector<int>& a, size_t step = 0) {
//base case
if (step + 1 >= a.size()) {
return;
}
else {
int temp_index {recursive_min(a, step + 1)};
if (a[step] > a[temp_index]) {
swap(a[step], a[temp_index]);
}
selectionSort(a, step + 1);
}
}
//---------------------------------------------------------
int main() {
vector<int> vec {11, 23, 2, 50, 3, 8, 1, 4, 5};
selectionSort(vec);
for (int i : vec) {
cout << i << " ";
}
}
Recursive Insertion Sort
#include <iostream>
#include <vector>
using namespace std;
int recursive_insert(vector<int>& a, int key, int i) {
//base case
if (i <= -1 || a[i] <= key) {
return i;
}
else {
a[i + 1] = a[i];
return recursive_insert(a, key, i - 1);
}
}
//-----------------------------------------------------------------------------
void insertion_sort(vector<int>& a, size_t j = 1) {
//base case
if (j >= a.size()) {
return;
}
else {
int key = a[j];
int i = recursive_insert(a, a[j], j - 1);
a[i + 1] = key;
insertion_sort(a, j + 1);
}
}
//-----------------------------------------------------------------------------
int main() {
vector<int> vec {11, 23, 2, 50, 3, 8, 1, 4, 5};
insertion_sort(vec);
for (int i : vec) {
cout << i << " ";
}
}
#include<stdio.h>
int * sort(int *p,int i,int j,int size)
{
if(i<size)
{
if(j<size-i-1)
{
if(p[j]>p[j+1])
{
int temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
else
{
j=-1;
++i;
}
p = sort(p,i,++j,size);
}
return p;
}
Below is how to use it
int main()
{
int array[] ={1,5,2,7,3};
int len = sizeof(array)/sizeof(int);
int *a = sort(array,0,0,len);
for(int i=0;i<len;i++)
{
printf("\n array[%d]->%d",i,a[i]);
}
}
I think you are looking for the Quicksort Algorithm
There are more ways to sort an array.
If you are trying to implement a loop recursively, you can check out a wikipedia article. It is well explained under "Recursion computer science".
Otherwise you can try to implement different sorting algorithms. The well known are Quicksort and Mergesort.
There are many sorting algorithms
Well, I'm writing a Python interpreter and didn't write loop yet. I got the codebase from some website and rewrite the loop by some recursion. It works. :D
def quickSort(arr, low, high):
def jLoop(low, high, pivot, i, j):
if j >= high:
temp = arr[high]
arr[high] = arr[i+1]
arr[i+1] = temp
return (i+1)
else:
if arr[j] <= pivot:
i = i+1
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return jLoop(low, high, pivot, i, j+1)
def partition(low, high):
i = (low - 1)
pivot = arr[high]
return jLoop(low, high, pivot, i, low)
def quick(low, high):
if low < high:
pi = partition(low, high)
quick(low, pi-1)
quick(pi+1, high)
quick(low, high)
return arr
my_list = [0, 6, 3, 1, 2, 4, 7, 5]
length = 8
print quickSort(my_list, 0, 7)
my_list = [9, 0, 8, 1, 7, 2, 6, 3, 5, 4]
length = 10
print quickSort(my_list, 0, 9)