Finding the smallest value in an array - c++

So I'm having some trouble with something. I have to create a function that will find the smallest number in an array. I know of one way to do it, using an overkill amount of if/else if, which won't do any good if the array size changes. I know using a for loop should do the trick but I can't figure out how to write it. Any push in the right direction would be greatly appreciated.
#include <iostream>
using namespace std;
int findLowest(int[]);
int main()
{
int AR[5] = {4, 87, 1, -3, 78};
cout << findLowest(AR);
return 0;
}
int findLowest(int AR[])
{
return lowest;
}

If you can change the function signature and include a header file that specifies general limits, you could do the following, which reads through the array in one pass:
#include <climits>
...
/* assumes AR_size > 0 */
int findLowest(int AR[], int AR_size)
{
int lowest = INT_MAX;
for (i = 0; i < AR_size; ++i) {
lowest = (AR[i] < lowest) ? AR[i] : lowest;
}
return lowest;
}

template<size_t N>
int findLowest(int (&ar)[N])
{
return *std::min_element(std::begin(ar), std::end(ar));
}
Note the usage of a template to make sure we get the size information from the caller.

#include <iostream>
#include <cassert>
using namespace std;
int findLowest(int ar[], const int& SIZE)
{
assert(("Error: the size of the array is zero. Make sure that ", SIZE > 0));
int lowest = ar[0];
for(int i=0; i<SIZE;i++)
{
if(lowest > ar[i])
lowest = ar[i];
}
return lowest;
}
int main()
{
const int SIZE(5);
int AR[5] = {11, 12, 10, 14, 15};
cout << findLowest(AR,SIZE);
return 0;
}

Instead of defining your own function to find the smallest number in your array, why do you not use the standard std::min_element function to do it for you? Create a std::vector object from the array, and let the min_element function do the job for you.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
#define ARRAY_SIZE 5
int main ( int argc, char **argv )
{
int ar [ ARRAY_SIZE ] = {4, 87, 1, -3, 78};
std::vector<int> arVector ( ar, ar + ARRAY_SIZE );
std::cout << *std::min_element ( arVector.begin ( ), arVector.end ( )) << std::endl;
return EXIT_SUCCESS;
}
Output:
-3

Related

Trouble with index

Write the find function, which takes a fixed integer vector reference and a single value integer and returns the index of the first occurrence of this value in the vector or the length of the vector if no value in it. The function should be adapted for use in the sample program
below. The function uses only the vector header file.
This is what I've done so far:
#include <vector>
#include <iostream>
using namespace std;
int find(const vector<int> &r ,int number)
{
int i=0;
int x;
for(i;i<r.size();++i)
{
if(r[i]==number)
{
break;
}
}
return 0;
}
int main()
{
int result = find(vector<int> {3, -1, 7, 12, -5, 7, 10}, 7);
cout << result << endl;
}
And, I'm stuck, I don't know how to return the index.
You should add return i; instead of breaking out of the loop
and maybe return -1 instead of 0 if the number is not found.
Return index i when found otherwise return 0 after the loop like this:
int find( const std::vector<int>& r, const int number )
{
for ( int i = 0; i < r.size(); ++i )
{
if ( r[i] == number )
{
return i;
}
}
return 0;
}
The x is unused in find function.
You should return i from your function

getting the nth largest number

I am trying to get the nth largest number of an array, I tried to sort the array then access the nth number by indexing; I have written this code:
#include <iostream>
using namespace std;
int largest(int a[],int k){
for (int i=0;i<=(sizeof(a)/sizeof(*a));i++){
for (int j=i+1;j<=(sizeof(a)/sizeof(*a));j++){
if(a[j]>a[i]){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a[k-1];
}
int main()
{
int a[]={3,2,1,0,5,10};
int m=largest(a,4);
cout<<m<<endl;
return 0;
}
and when I print out m it appears to be 5 while it is expected to be 2, when I tried to replace int m=largest(a,4); with m=largest(a,1); it printed 2 so it appears that he prints the index of the array a but without sorting it, any idea?
The problem lies in the use of sizeof(a)/sizeof(*a) to get the number of elements of the array. sizeof(a) is the size of a pointer.
You need to pass the size of the array to the function.
int largest(int a[], int size, int k){
for (int i=0;i<size;i++){
for (int j=i+1;j<size;j++){
...
}
}
}
and call it with
int m = largest(a, 6, 4);
There are three problems with your code.
First, when you pass the array as an argument to your function, it decays into a pointer. So the function can never know the size of the array without additional information. It is main()'s job to find the size of the array and pass that information along to largest().
Second, you have an off-by-one error in your code, because you are attempting to iterate from 0 to the number of elements in the array.
The following will work:
#include <iostream>
using namespace std;
int largest(int a[],int k, int n){
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (a[j] > a[i]){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[k-1];
}
int main()
{
int a[] = {3, 2, 1, 0, 5, 10};
int k = 4;
int m = largest(a, k, sizeof a/ sizeof *a);
cout << m << endl;
}
At last but not least, you have nasty side effects in your function. If you have a function that is supposed to find the largest element of the array, it shouldn't modify the entire array in order to do so.
You can make a copy of the original array and sort it. Or you can implement a k-element sort algorithm. Either way you shouldn't change user data just to find some statistic from it.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[]={3,2,1,0,5,10};
std::sort(a, a+6, greater<int>() ); // Sort an array of 6 elements in greatest-first order.
cout<<a[3]<<endl; // Show the 4th element from the front.
return 0;
}
UPD: There are STL algorithm to use: std::nth_element.
#include <iostream>
#include <algorithm>
int main(){
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<std::nth_element(arr, arr + k, arr + length, std::greater<int>());
}
Also, if you want to implement it by yourselt you can do such thing based on quick sort:
#include <iostream>
#include <algorithm>
template<class T>
T largest_k(T* a, size_t left, size_t right, size_t k) {
if(left>=right)
return a[k-1];
size_t i = left, j = right;
T middle = a[ i + (j-i) / 2 ];
do {
while ( a[i] > middle ) i++;
while ( a[j] < middle ) j--;
if (i <= j) {
std::swap(a[i], a[j]);
i++; j--;
}
} while ( i<=j );
// We need to go deeper only for needed part of a
if ( k<=j+1 )
return largest_k(a, left, j, k);
if ( k>= i )
return largest_k(a, i, right, k);
}
int main()
{
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<largest_k<int>(arr, 0, length-1, k);
}

C++ how to sort the values in an array based on magnitude?

For instance I have an array:
array[5] = {-3, 4, 5, 1, -2}
I am trying to sort it as {1, -2, -3, 4, 5}.
I tried doing bubble sort with abs value but that did not work.
There are plenty of ways to sort like that, and one of the most easiest, in fact, is to use, the std::sort() function from <algorithm>... (Just remember to set up your compiler for C++11 or above)
Create an advanced_absolute function (As pointed out in comments):
constexpr auto min_abs(int x)
{
return x < 0 ? signed(unsigned(-1)) - signed(unsigned(x) + 1U) : x;
}
And sort:
std::sort(std::begin(array), std::end(array), [](int const num1, int const num2) -> bool
{
return (num1 == INT_MIN ? min_abs(num1) : std::abs(num1)) < (num2 == INT_MIN ? min_abs(num2) : std::abs(num2));
});
and include these at the top...
#include <algorithm>
#include <iterator> // This is already included the <iostream> and other headers dependent on this header...
You can use the following code:
#include <stdio.h>
#include <stdlib.h>
#define size 5
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (abs(arr[j]) > abs(arr[j+1]))
swap(&arr[j], &arr[j+1]);
}
int main()
{
int array[size] = {-3, 4, 5, 1, -2};
bubbleSort(array, size);
for (int i=0; i<size; i++)
{
printf("%d ", array[i]);
}
return 0;
}
It can give you a better understanding of how things would work at fine grain level.
Bubblesort function in C is taken from here
Following ruk's idea, but simplified:
#include <algorithm>
#include <iterator>
#include <cstdlib>
// ...
std::sort(std::begin(array), std::end(array), [](int const num1, int const num2)
{
// Don't call std::abs(INT_MIN), just return the correct value directly.
if (num1==INT_MIN) return false; // First, because INT_MIN<INT_MIN==false
if (num2==INT_MIN) return true;
// If we get here, neither value is INT_MIN so we can safely call std::abs
return (std::abs(num1) < std::abs(num2));
});

Find in array the biggest multiple and write it vica versa

I was given a task:
it is given an array of five numbers
First - Find all numbers that are multiples of four
Second - Find the biggest of them and write it vice versa.
I have written a code.
#include <iostream>
#include <iomanip>
using namespace std;
#define size 12
int main()
{
int new_max=0;
int a1, a2;
int i=0, j=0;
int a, b, c=0;
int u[size]={38,12,36,45,16,46,14,19,54,53,95, 98};
int max=0;
cout<<"Array: \n";
for(i=0; i<size; i++)
cout<<u[i]<<" \n";
for (int i=0; i<size; i++)
{
if (u[i]%4==0)
{
cout<<"array "<<u[i]<<" \n";
for (int j=0; j<size; j++)
{
if(max<u[i])
{
max=u[i];
}}}}
cout<<"max "<<max<<endl;
while(max > 0)
{
new_max = new_max*10 + ( max % 10);
max = max/10;
}
cout << new_max << endl;
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
#include <array>
int main() {
std::array<int, 5> input = { 36, 12, 38, 45, 16 };
auto validRangeEnd = std::remove_if(std::begin(input),
std::end(input),
[](int i){ return i % 4 != 0; });
// Now std::begin(input) -> validRangeEnd contain the ones divisible by 4
auto max = std::max_element(std::begin(input), validRangeEnd);
// Max contains the max number from the filtered range
auto stringMax = std::to_string(*max);
std::reverse(std::begin(stringMax), std::end(stringMax));
// Reverse reverses the max number
std::cout << stringMax;
}
By no means optimal but I feel it's useful for educational purposes :).
(Both remove_if and max_elements do a pass so I'll re-examine some stuff that I don't need to but this is a good algorithmic representation of the problem anyway. Also, no loops, look! :))

Deque Implementation

I have question regarding the code I found on Internet which uses a deque for finding the max of the element --
#include <iostream>
#include <deque>
using namespace std;
void test(int arr[], int n)
{
std::deque<int> Qi(n);
int i;
for (i = 0; i < n; ++i)
{
while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back(); // Remove from rear
Qi.push_back(i);
}
cout << arr[Qi.front()];
}
// Driver program to test above functions
int main()
{
int arr[] = {12, 1, 78, 90, 57, 89, 56};
int n = sizeof(arr)/sizeof(arr[0]);
test(arr, n);
return 0;
}
My Question is how is Qi.front() giving the right index when I have not done any Qi.push_front() ?
But the following code gives me a 0
void test(int arr[], int n)
{
std::deque<int> Qi(n);
int i;
for (i = 0; i < n; ++i)
{
Qi.push_back(i);
}
cout << arr[Qi.front()];
}
Sorry If I am sounding stupid .. New to deques ...
Thanks
std::deque<int> Qi(n); creates a deque with n elements, all zero. The push_back operations add further elements at the back, so afterwards the deque has 2 * n elements. Qi.front() is identical to Qi[0].
All this is well-documented, e.g. here.