binary search not returning the index - c++

this is my c++ program for binary search and for some reason it is not returning the index of the element that I searched
#include <iostream>
//using namespace std;
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int binarySearch(struct array arr, int element) {
int l, h;
l = 0;
h = arr.length;
for (int i = 0; l <= h; i++) {
int mid = (l + h) / 2;
if (arr.A[mid] == element)
return mid;
else if (arr.A[mid] < element)
h = mid -1;
else
l = mid+1;
std::cout << mid << std::endl;
}
return -1;
}
int main()
{
struct array arr = {{1,2,3,4,5,6,7}, 10, 7};
int* p;
displayArray(arr);
std::cout << binarySearch(arr, 6) << std::endl;
}
I tried everything and still, it is not working for some reason
am I missing something here?

change position of l, h. you need to growth mid value if you find bigger value, the other way around, too.

#include <iostream>
using namespace std;
struct array1 {
int A[10];
int size;
int length;
};
void displayArray(struct array1 arr) {
std::cout << "the elements are :-" << std::endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
void binarySearch(struct array1 arr, int element) {
int l, h;
l = 0;
h = arr.length;
int mid = arr.length / 2;
if (arr.A[mid] == element)
cout << "i am on index number=" << mid;
else if ( element< arr.A[mid])
for (int i = 0; 1; i++)
{
if (arr.A[i] == element)
{
cout << "i am on index number=" << i;
break;
}
}
else
for (int i = mid; 1; i++)
{
if (arr.A[i] == element)
{
cout << "i am on index number=" << i;
break;
}
}
}
int main()
{
struct array1 arr = { {1,2,3,4,5,6,7}, 10, 7 };
displayArray(arr);
binarySearch(arr, 6);
return 0;

Related

How do I have multiple rand generators in one code?

I am writing a code to sort an array of random integers using four sorting methods bubble, selection, shell and quick sort. I'm using the same code as a rand generator to create random integers which can be sorted by the sort functions. My issue is that when I run multiple sort methods at the same time; my rand generators create the same set of integers for the arrays. How do I fix this so I can have parallel rand generators in the same program? I cannot use c++11 array or STL vector.
main.cpp
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "AssortedSorter.h"
using namespace std;
int main() {
AssortedSorter q, q2;
int UserNumOfNumbers;
int bchoice;
cout << " We pick array size (0) or you pick array size (1): ";
cin >> bchoice;
while (bchoice == 0) {
UserNumOfNumbers = 10000;
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++) {
array[i] = (rand() %200002) + 1;
}
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
// long b = array[i];
q.quicksort(array, 0, UserNumOfNumbers);
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] << endl;
// q.quicksort(array, 0, UserNumOfNumbers);
}
//q.bubbleSort(array, UserNumOfNumbers);}
// q.selectionSort(array, UserNumOfNumbers);}
return 0;
}
while (bchoice == 1) {
cout << "Enter a number between 10 and 20000: ";
cin >> UserNumOfNumbers;
while (UserNumOfNumbers < 10 || UserNumOfNumbers > 20000) {
cout << "Invalid entry! Please enter a valid value: ";
cin >> UserNumOfNumbers;
}
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++)
array[i] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] <</*(rand() %200002) + 1 */endl;
}
int arra[UserNumOfNumbers];
srand(std::time(NULL));
for (int j = 0; j < UserNumOfNumbers; j++)
arra[j] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int j = 0; j < UserNumOfNumbers; j++) {
q.quicksort(arra, 0, UserNumOfNumbers);
cout << " Number of Elements " << j + 1 << "::" << arra[j] << endl;
}
/*int arran[UserNumOfNumbers];
srand(std::time(0));
for (int k = 0; k < UserNumOfNumbers; k++)
arran[k] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int k = 0; k < UserNumOfNumbers; k++) {
q.selectionSort(arran, UserNumOfNumbers);
cout << " Number of Elements " << k + 1 << "::" <<(rand() %200001) + 1 << endl;}*/
break;
}
}
AssortedSorter.cpp
#include <iostream>
#include "AssortedSorter.h"
//long array;
using namespace std;
int AssortedSorter::partition(int array[], int start, int stop){
int up = start, down = stop - 1, part = array[stop];
long loopCountQ, swapCountQ;
if (stop <= start)
return start;
while (true)
{
while (array[up] < part){
/* loopCountQ++;
cout << " Loop Count++: " << loopCountQ << endl;*/
up++;}
while ((part < array[down]) && (up < down)){
/* loopCountQ++;
cout << " Loop Count--: " << loopCountQ << endl;*/
down--;}
if (up >= down)
break;
swap(array[up], array[down]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
up++;
down--;}
}
swap(array[up], array[stop]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
return up;}
}
int AssortedSorter ::getquicksort() const {
return *b;
}
void AssortedSorter :: quicksort(int a[], int start, int stop){
int i, s = 0, stack[20001];
// b = a;
//long * array = (a);
stack[s++] = start;
stack[s++] = stop;
while ( s > 0)
{
stop = stack[--s];
start = stack[--s];
if (start >= stop) continue;
i = partition(a, start, stop);
if
(i - start > stop - i)
{
stack[s++] = start; stack[s++] = i - 1;
stack[s++] = i + 1; stack[s++] = stop;
}
else {
stack[s++] = i + 1; stack[s++] = stop;
stack[s++] = start; stack[s++] = i - 1;
}
}
}
void AssortedSorter:: bubbleSort(int array[], int size) {
int maxElement;
int index;
//long loopcount = 0;
for (maxElement = size - 1; maxElement > 0; maxElement--) {
for (index = 0; index < maxElement; index++) {
if (array[index] > array[index + 1]) {/*loopcount++;
cout << " Loop count: " << loopcount << endl;*/
swap(array[index], array[index + 1]);
}
}
}
}
/*void AssortedSorter :: swap(int &a, int &b){
/* long int swapcount = 0;
{swapcount++;
cout << "Swap count: " << swapcount << endl;}
int temp = a;
a = b;
b = temp;
}*/
void AssortedSorter::selectionSort(int array[], int size)
{
int minIndex, minValue;
long int loopcountsel = 0;
for (int start = 0; start < (size - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++)
{
if(array[index] < minValue)
{
loopcountsel++;
// cout << "Loop count: " << loopcountsel << endl;
}
if(array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void AssortedSorter :: swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
AssortedSorter.h
#ifndef SORTER_ASSORTEDSORTER_H
#define SORTER_ASSORTEDSORTER_H
class AssortedSorter {
public:
void quicksort(int a[], int, int);
int getquicksort() const;
int partition(int [], int, int);
void bubbleSort(int[], int);
int getbubblesort() const;
//void swap(int & , int &);
int getswap() const;
void selectionSort(int[], int);
void swap(int &, int &);
private:
int* b;
};
#endif //SORTER_ASSORTEDSORTER_H

SelectionSort in c++ not sorting*

I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.

Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted

I am running project called Horse Board Game. When it got almost done, it happened an error at the end of the execution part. The error is:
Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted.
Where is the mistake here? Everything seems to work properly, only that error occurs.
#include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;
void printHorizontalLine(int size) {
for (int i = 0; i < size; i++) {
cout << " -----------";
}
cout << "\n";
}
void printVerticalLine(int size) {
cout << "|";
for (int i = 0; i < size; i++) {
cout << " |";
}
cout << "\n";
}
void displayBoard(int size, char board[50][50]) {
for (int i = 0; i < size; i++) {
printHorizontalLine(size);
printVerticalLine(size);
cout << "|";
if (i % 2 == 0) {
for (int j = 0; j < size; j++) {
cout << " " << board[i][j] << " |";
}
}
else {
for (int j = size - 1; j >= 0; j--) {
cout << " " << board[i][j] << " |";
}
}
cout << "\n";
printVerticalLine(size);
}
printHorizontalLine(size);
}
void init_board(char board[50][50], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
void enteringPlayerName(char name[], int n) {
for (int i = 0; i < n; i++) {
cout << "Player " << i + 1 << " enter name: " << "\n";
cin >> name[i];
}
}
void beginningPos(int n, int pos[]) {
for (int i = 0; i < n; i++) {
pos[i] = -1;
}
}
void rollDice(int max, char board[50][50], int pos[], char name[], int size, int n, int cur) {
int step = rand() % max + 1;
cout << name[cur] << " roll " << step << "\n";
if (step + pos[cur] > size * size - 1) {
cout << "Cannot move forward\n";
}
else {
pos[cur] += step;
for (int i = 0; i < n; i++) {
if ((pos[cur] == pos[i]) && (i != cur)) {
pos[i] = -1;
cout << name[i] << " is kicked to the Start!!\n";
}
}
}
}
void updatingBoard(char board[50][50], char name[], int pos[], int n, int size) {
init_board(board, size);
for (int k = 0; k < n; k++)
{
int x, i, j;
x = pos[k];
i = x / size;
j = x % size;
board[i][j] = name[k];
}
}
char playGame(int max, int n, int size, char board[50][50], int pos[], char name[], int finish_point) {
char winner = ' ';
int cur_turn = 0;
while (winner == ' ') {
rollDice(max, board, pos, name, size, n, cur_turn % n);
updatingBoard(board, name, pos, n, size);
displayBoard(size, board);
if (pos[cur_turn % n] == finish_point) winner = name[cur_turn % n];
cur_turn++;
}
return winner;
}
int main() {
int size, n;
cin >> size;
cin >> n;
const int MAX = 50;
int max = 3;
int pos[200];
char name[10];
char winner = ' ';
char board[MAX][MAX];
int finish_point = size * size - 1;
srand(time(0));
enteringPlayerName(name, n);
init_board(board, size);
beginningPos(n, pos);
winner = playGame(max, n, size, board, pos, name, finish_point);
if (winner == ' ') cout << "Tie game";
else cout << winner << " is the winner";
return 0;
}```
When I set size to 4 and n to 2 as recommended in the comments section, then the line
board[i][j] = name[k];
in the function updatingBoard causes a buffer underflow.
The first time that line is executed, i has the value 0 and j has the value 0, which is ok, but the second time that line is executed, i has the value 0 but j has the value -1. This is obviously wrong, because board[0][-1] is accessing the array out of bounds.
That is the reason for the error message that you are receiving.
You can easily see this by running your program line by line in a debugger.

I'm trying implement mergesort using array in a class, but all i get are random values, mostly zeros

I don't know if i can operate like this on my array, or i should create some copy of it. Still i have other algorithms to implement that's why i thought of using array in this class. I think the problem is with using this array ,,arr", because when i printed the values in the separate_and_merge function, they were mostly 0, or trashes, i don't know what i have done wrong.
#include <iostream>
template<typename TYPE, int SIZE>
class Array
{
private:
TYPE* arr;
public:
void DisplayArray();
void separate_and_merge(int begin, int middle, int end);
void merge_sorting(int begin, int end);
void getRandomArray();
Array();
};
template<typename TYPE, int SIZE>
Array<TYPE, SIZE>::Array()
{
arr = new TYPE[SIZE];
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::separate_and_merge(int begin, int middle, int end)
{
int size_left = middle - begin + 1; //rozmair lewej podtablicy
int size_right = end - middle; // rozmiar prawej podtablicy
TYPE arr1[size_left]; // inicjacja tablic
TYPE arr2[size_right];
// podpisanie wartosci pod tablice
for (int i = 0; i < size_left; i++)
{
arr1[i] = arr[i];
}
for (int j = 0; j < size_right; j++)
{
arr2[j] = arr[j + middle + 1];
}
for (int i = 0; i < SIZE; i++)
{
}
//scalenie wartosci 2 podtablic w 1 tablice
int i = 0;
int j = 0;
int begin1 = begin; //aktualny indeks scalanej tablicy
while (i <= size_left && j <= size_right)
{
if (arr1[i] < arr2[j])
{
arr[begin1] = arr1[i];
i++;
}
else
{
arr[begin1] = arr2[j];
j++;
}
begin1++;
}
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::merge_sorting(int begin, int end)
{
if (begin < end)
{
int middle = (begin + end) / 2; // srodek tablicy
merge_sorting(begin, middle);
merge_sorting(middle + 1, end);
separate_and_merge(begin, middle, end);
}
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::DisplayArray()
{
for (int i = 0; i < SIZE; i++)
{
std::cout << arr[i] << std::endl;
}
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::getRandomArray()
{
srand(time(NULL));
for (int i = 0; i < SIZE; i++)
{
arr[i] = std::rand();
}
}
int main() {
const int size = 10;
Array<int, size> tmp;
tmp.getRandomArray();
tmp.DisplayArray();
std::cout << std::endl << std::endl << std::endl << std::endl;
tmp.merge_sorting(0, size);
tmp.DisplayArray();
return 0;
}
Some problems I found
int main() {
...
tmp.merge_sorting(0, size);
...
return 0;
}
From above, you are passing 0, size to merge_sorting() method. C++ is zero based indexing, so that the index of last element of tmp array is size-1. You'd better do tmp.merge_sorting(0, size-1);.
void Array<TYPE, SIZE>::separate_and_merge(int begin, int middle, int end)
{
...
// podpisanie wartosci pod tablice
for (int i = 0; i < size_left; i++)
{
arr1[i] = arr[i];
}
...
}
arr1[i] = arr[i] should be arr1[i] = arr[begin + i]. Because in this function, you are considering the [begin, end) part of the arr.
TYPE arr1[size_left]; // inicjacja tablic
TYPE arr2[size_right];
while (i <= size_left && j <= size_right)
{
if (arr1[i] < arr2[j])
{
arr[begin1] = arr1[i];
i++;
}
else
{
arr[begin1] = arr2[j];
j++;
}
begin1++;
}
It shouldn't have = in i <= size_left && j <= size_right. Take i=size_left as an example, since the size of arr1 is size_left and C++ is zero indexed, it will cause index out of range error.
Moreover, have you considered the case that size_left != size_right? Take size_left > size_right as an example. After the above while loop, there remain some elements in arr1. So you need consider the remaining elements of arr1 and arr2.
// Copy the remaining elements of arr1[],
// if there are any
while (i < size_left) {
arr[begin1] = arr1[i];
i++;
begin1++;
}
// Copy the remaining elements of arr2[],
// if there are any
while (j < size_right) {
arr[begin1] = arr2[j];
j++;
begin1++;
}
The whole code is
#include <iostream>
template<typename TYPE, int SIZE>
class Array
{
private:
TYPE* arr;
public:
void DisplayArray();
void separate_and_merge(int begin, int middle, int end);
void merge_sorting(int begin, int end);
void getRandomArray();
Array();
};
template<typename TYPE, int SIZE>
Array<TYPE, SIZE>::Array()
{
arr = new TYPE[SIZE];
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::separate_and_merge(int begin, int middle, int end)
{
int size_left = middle - begin + 1; //rozmair lewej podtablicy
int size_right = end - middle; // rozmiar prawej podtablicy
TYPE arr1[size_left]; // inicjacja tablic
TYPE arr2[size_right];
// podpisanie wartosci pod tablice
for (int i = 0; i < size_left; i++)
{
arr1[i] = arr[begin + i];
}
for (int j = 0; j < size_right; j++)
{
arr2[j] = arr[j + middle + 1];
}
std::cout << "+++++++[" << begin << ", " << end << ")+++++++++" << std::endl;
std::cout << "begin: " << begin << std::endl;
std::cout << "middle: " << middle << std::endl;
std::cout << "end: " << end << std::endl;
std::cout << "size_left: " << size_left << std::endl;
std::cout << "size_right: " << size_right << std::endl;
std::cout << "+++++++++++++++++++++" << std::endl;
std::cout << "======[0, SIZE)==========" << std::endl;
for (int i = 0; i < SIZE; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "!!!!![begin, end)!!!!" << std::endl;
for (int i = begin; i < end; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "!!!!!!!!!!!!!!!!!!!!!" << std::endl;
std::cout << "#####[begin, mid)####" << std::endl;
for (int i = 0; i < size_left; i++)
{
std::cout << arr1[i] << " ";
}
std::cout << std::endl;
std::cout << "#####################" << std::endl;
std::cout << "$$$$$[mid, end)$$$$" << std::endl;
for (int i = 0; i < size_right ; i++)
{
std::cout << arr2[i] << " ";
}
std::cout << std::endl;
std::cout << "$$$$$$$$$$$$$$$$$$$$$" << std::endl;
//scalenie wartosci 2 podtablic w 1 tablice
int i = 0;
int j = 0;
int begin1 = begin; //aktualny indeks scalanej tablicy
while (i < size_left && j < size_right)
{
if (arr1[i] < arr2[j])
{
arr[begin1] = arr1[i];
i++;
}
else
{
arr[begin1] = arr2[j];
j++;
}
begin1++;
}
// Copy the remaining elements of
// arr1[], if there are any
while (i < size_left) {
arr[begin1] = arr1[i];
i++;
begin1++;
}
// Copy the remaining elements of
// arr2[], if there are any
while (j < size_right) {
arr[begin1] = arr2[j];
j++;
begin1++;
}
std::cout << "======[begin, end)=======" << std::endl;
for (int i = begin; i < end; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "======[0, SIZE)==========" << std::endl;
for (int i = 0; i < SIZE; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl << "=========================" << std::endl << std::endl;
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::merge_sorting(int begin, int end)
{
if (begin < end)
{
int middle = (begin + end) / 2; // srodek tablicy
merge_sorting(begin, middle);
merge_sorting(middle + 1, end);
separate_and_merge(begin, middle, end);
}
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::DisplayArray()
{
for (int i = 0; i < SIZE; i++)
{
std::cout << arr[i] << std::endl;
}
}
template<typename TYPE, int SIZE>
void Array<TYPE, SIZE>::getRandomArray()
{
srand(time(NULL));
for (int i = 0; i < SIZE; i++)
{
arr[i] = std::rand();
}
}
int main() {
const int size = 12;
Array<int, size> tmp;
tmp.getRandomArray();
tmp.DisplayArray();
std::cout << std::endl << std::endl << std::endl << std::endl;
tmp.merge_sorting(0, size-1);
std::cout << std::endl << std::endl;
tmp.DisplayArray();
return 0;
}

finding the most repeated elements in an array with length n

const int N=10;
int main()
{
int arr[N]={4,4,6,4,6,6,7,9,9,9};
for (int i = 0; i < N; i++)
for (int j=i+1; j<N; j++)
{
if (arr[i]==arr[j])
cout << arr[i];
}
return 0;
}
This gives all the repeated elements (meaning it will give 444,666,999). My problem is that I want the output to be just 4,6,9 and not that 4 was repeated three times. Obviously I gave my global constant a value of 10 but how can i do this for an "n" (unknown) number. Thanks.
At the beginning sort array
sort(arr, arr + n);
Then iterate and find the count of the most repeated element, you can do that like this :
int maxCnt = 0;
int curCnt = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) curCnt++;
else
{
maxCnt = max(maxCnt, curCnt);
curCnt = 1;
}
}
maxCnt = max(maxCnt, curCnt);
then iterate again accumulating curCnt and when curCnt == maxCnt output number
curCnt = 1;
for (int i = 1; i < n; i++) {
if (curCnt == maxCnt) cout << arr[i - 1] << ' ';
if (arr[i] == arr[i - 1]) {
curCnt++;
}
else curCnt = 1;
}
if (curCnt == maxCnt) cout << arr[n - 1] << endl;
This solution will output the most repeated numbers only once.
Use "range based for loop" for unknown array size (N).
Use std::map to calculate the count for each element.
Here is the code:
#include <map>
#include <iostream>
using namespace std;
int main()
{
const int arr[]{ 4,4,6,4,6,6,7,9,9,9 };
// Get count for each element.
map<int, int> elementCount;
for (const auto& e : arr)
{
elementCount[e] += 1;
}
// Get the highest count.
int highestCount = 0;
for (const auto& e : elementCount)
{
cout << e.first << " " << e.second << endl;
if (e.second > highestCount)
{
highestCount = e.second;
}
}
// Get the elements with the hightest count.
cout << endl << "Elements with the hightest count:" << endl;
for (const auto& e : elementCount)
{
if (e.second == highestCount)
{
cout << e.first << " ";
}
}
cout << endl;
return 0;
}