Find the largest element of an array in c++ - c++

there is an array containing elements from 1 to 10 and any of the element can be repeat you have to find the index of the largest element.
if there is more than 2 similar largest elements then show the smallest index of those elements.
like [2,2,1,0,0]
then you will print 0.

#include<bits/stdc++.h>
using namespace std;
int main()
{
while(1){
int n;
cin>>n;
multimap<int, int> m;
int num;
for(int i=1; i<=n; i++)
{
cin>>num;
m.insert({num,i});
}
int capacity = 5;
int arr[capacity];
for(int i=0; i<capacity; i++){
arr[i] = m.count(i+1);
cout<<i<<" is :\t"<<arr[i]<<"times\n";
}
int a;
a = max_element(arr,arr+capacity)-arr;//it was my doubt section
cout<<a+1;
}
}

Related

Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even

For the given question I have come up with the following code. But it doesn't seem to solve the problem. Please have a look and suggest changes.
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int maxim=INT_MIN;
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=arr[j];
if (sum%2==0){
int len=n-i;
maxim=max(maxim,len);
}
}
}
cout<<maxim;
return 0;
}
I think there is a bug with this original line " int len=n-i " in the second for loop because you miscalculate the len here.
Maybe, you should calculate the len with this new formula " int len= j - i + 1 ", which seems to be the accurate len.
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int maxim=INT_MIN;
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=arr[j];
if (sum%2==0){
int len= j - i + 1; // Calculate len here
maxim=max(maxim,len);
}
}
}
cout<<maxim;
return 0;
}
Note : Your algorithm above has the time complexity of O(n^2). There are definitely other better algorithms that have the time complexity of O(n) to solve this problem.
First check if the total sum of the array is even. If the total sum of the array is even then the answer will be N.
If the total sum of the array is not even, means it is ODD. So, the idea is to find an odd element from the array such that excluding that element and comparing the length of both parts of the array we can obtain the max length of the subarray with even sum.
int maxLength(int a[], int n){
int sum = 0, len = 0;
// Check if sum of complete array is even
for (int i = 0; i < n; i++)
sum += a[i];
if (sum % 2 == 0) // total sum is already even
return n;
// Find an index i such the a[i] is odd
// and compare length of both halfs excluding
// a[i] to find max length subarray
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 1)
len = max(len, max(n - i - 1, i));
}
return len;
}

Bubble sort ignoring the first element of the array

I was doing my homework but don't know why bubble sort is not working. it is making first element of the array zero due to some unknown reason.
#include <iostream>
using namespace std;
int main()
{
int *arr,s;
cout<<"Enter the quantity of numbers ";
cin>>s;
arr=new int[s];
for(int i=0;i<s;i++)
{
cout<<"Enter number "<<i+1<<" ";
cin>>*(arr+i);
}
int temp;
for(int j=0;j<s;j++)
{
for(int k=0;k<(s-j);k++)
{
if(*(arr+k)>*(arr+k+1))
{
temp=*(arr+k);
*(arr+k)=*(arr+k+1);
*(arr+k+1)=temp;
}
}
}
for(int x=0;x<s;x++)
{
cout<<*(arr+x)<<"\t";
}
cout<<endl;
return 0;
}
OUTPUT
Enter the quantity of numbers 5
Enter number 1 4
Enter number 2 33
Enter number 3 22
Enter number 4 1
Enter number 5 3
0 1 3 4 22
I don't know why first element is getting zero. and if I run it without bubble sort loops it runs perfectly but don't with those loops.
In this for loop
for(int k=0;k<(s-j);k++)
{
if(*(arr+k)>*(arr+k+1))
^^^^^^^
{
temp=*(arr+k);
*(arr+k)=*(arr+k+1);
*(arr+k+1)=temp;
}
there is an attempt tp access memory beyond the array when j is equal to 0 and k is equal to s - 1. That is in this case k + 1 is equal to s though the valid range of indices is [0, s-1].
At least change the loops the following way
for(int j=0;j<s;j++)
{
for(int k = 1;k<(s-j);k++)
{
if(*(arr+k) < *(arr+k-1))
{
int temp=*(arr+k);
*(arr+k)=*(arr+k-1);
*(arr+k-1)=temp;
}
}
}
Your use of the index is off. You are picking up garbage values from outside your valid range (they just happen to be zeros). An easier style might help detect the problem.
for(int j=0;j<s;j++)
{
for(int k=1;k<s;k++)
{
if(arr[k-1]>arr[k])
{
int temp=arr[k];
arr[k]=arr[k-1];
arr[k-1]=temp;
}
Code
#include <bits/stdc++.h>
using namespace std;
int N, a[10050];
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%d" , &a[i]);
for (int k = 0; k < N; k++) {
int mn = k;
for (int i = k+1; i < N; ++i) {
if (a[i] < a[mn]) mn = i;
}
swap(a[k], a[mn]);
}
for (int i = 0; i < N; i++) printf("%d " , a[i]);
}
Explanation
In bubble sort, you swap the elements recursively. Here is a 15-line code. Hope it helps.

Please explain the code in this count sort

I was learning count sort from tutorial and my C++ source code is given below:
#include <iostream>
#include <string.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int output[size];
//declare count array
int count[size];
//initialize count[] with zero
//memset ( void * ptr, int value, size_t num )
memset(count, 0, sizeof(count));
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
/*
Modify the count array such that each element at
each index stores the sum of previous counts.
*/
// i=1 because, previous is 0 due to avoid -1
for(int i=1; i<size; i++){
count[i] += count[i-1];
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
//***********THIS LINE***********
output[count[arr[i]]-1] = arr[i];
count[arr[i]]--;
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
// your code goes here
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}
I understand about taking sorted array in output array.However why we need to decrements the output index by -1:
output[count[arr[i]]-1] = arr[i];
I didn't understand this part. I try with only output[count[arr[i]]] but it doesn't gave me the correct sorted array.
The array of counts was converted in to an array of ending indices, point one past the end of each logical bucket, so 1 is subtracted from each index. This could be combined to use pre-decrement, and the array scanned backwards:
for(i=size; i; ){
i--;
output[--count[arr[i]]] = arr[i];
}
Getting back to the counts after they are summed up, note that count[0] contains a count of all the elements equal to zero, and count[1] contains a count of all elements == zero and all elements == 1, and so on, so count[0] is the logical size of the bucket that will contain the zeroes, and the size is 1 greater than the index to the last element. The same logic applies to count[1] and so on.
Example code where the counts are converted into starting indices. output[] converted to use new (to avoid stack overflow and some compilers don't support variable length arrays). count[10] assumes the range of numbers is limited to 0 through 9.
#include <iostream>
#include <stdlib.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int * output = new int[size];
//declare count array
// assumes range of values is 0 to 9
int count[10];
//initialize count[] with zero
for(int i=0; i<size; i++)
count[i] = 0;
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
// convert counts into starting indices (this is the main change)
int sum = 0, tmp;
for(int i=0; i<size; i++){
tmp = count[i];
count[i] = sum;
sum += tmp;
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
output[count[arr[i]]++] = arr[i];
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
delete[] output;
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}

For loop don't work properly for more than one array in C++

I have ruby version of this program & trying to do the same in C++
The input must be:
2 # Number of pairs
562 -881 # First pair
310 -385 # Second pair
And output:
-319
-75
It's working fine with one array of 2 numbers and breaks if pairs > 2. What's wrong in my for loops?
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum << endl;
}
return 0;
}
Thanks for any help!
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
In first iteration values are entered in arr and again in second iteration previous values are overwritten (similar in next iterations if any ). This is the problem .
Solution -
#include <iostream>
using namespace std;
int main() {
int iter;
cin >> iter;
int arr[2];
int sum[iter]; // declare sum as array with iter number of elements
for(int i=0;i<iter;i++){
sum[i]=0; // initialize elements of sum to 0
}
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n]; // take iput
sum[i]+=arr[n]; // add numbers and store in sum
}
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum[i] << endl; // print values in sum after taing all inputs
}
return 0;
}
You're overwriting the contents of arr on each iteration of the loop. Try something like this (live demo here):
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
cout << sum << endl;
}
return 0;
}

Given an array of integers A(20). Put Min element in the beginning of the array

Task is: Given an array of 20 integers A(20). Find the min positive integer in it and put it in the beginning of the array. Show the initial and changed arrays.
My code is (it works now):
#include <iostream>
using namespace std;
int main(){
int arrayA[20]={6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
int min=arrayA[0];
int i, minplace;
//array's showing in the screen
cout<<"Array A: \n";
for(i=0; i<20; i++)
cout<<arrayA[i]<<" ";
cout<<endl;
//min value of array's element
for(int i=0; i<20; i++)
if (arrayA[i]<min)
{
min=arrayA[i];
minplace=i;
}
cout<<"Min element's value of the array A: "<<min<<endl;
//array 2
int arrayB[21]={min,6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
//array's showing in the screen
cout<<"Array B: \n";
for(i=0; i<21; i++)
cout<<arrayB[i]<<" ";
cout<<endl;
int k=minplace+1;
int n=21;
for (int i=minplace+1; i<n; i++)
arrayB[i]=arrayB[i+1];
n=n-1;
cout<<"Array with deleted element: "<<endl;
for (int i=0; i<n; i++)
cout<<arrayB[i]<<" ";
return 0;
}
THIS CODE WORKS NOW.
This is a very vague question but I did notice that while you are using the variable X, you are never assigning it to anything.
This is a much better approach of doing this which utilizes only a single array and is more precise and clean. Hope that this might help someone in learning.
#include <iostream>
using namespace std;
int main(){
int arrSize = 20;
int myArray[20] = {6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
cout<<"Initial Array:\t";
/* loop for printing the initial array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i]<< " ";
/* assuming the first element of the array is the minimum */
int minIndex = 0;
int min = myArray[minIndex];
/* loop for finding the minimum value */
for(int i = 0; i<arrSize; i++){
/* condition for checking if the current element is the minimum */
if(myArray[i]<min){
min = myArray[i];
minIndex = i;
}
}
/* swaping the first element of the array with the minimum element */
myArray[minIndex] = myArray[0];
myArray[0] = min;
cout<<"\nFinal Array:\t";
/* loop for printing the final array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i] << " ";
return 0;
}