Heap Array not working - c++

I am writing a program to build a heap array from a usual array and it just doesn't work.
We have to use this sudo code which I used to write my rebuildHeap function but I don't know what I am doing wrong. Could someone spot any mistakes?
rebuildHeap is used after the replacement node has taken the place of root
rebuildHeap(heap, index, lastIndex)
1 if (index * 2 + 1 <= lastIndex)
1 leftKey = heap[index*2+1].key
2 if (index * 2 + 2 > lastIndex)
1 largeChildIndex = index * 2 + 1
3 else
1 rightKey = heap[index*2+2].key
2 if (leftKey > rightKey)
1 largeChildIndex = index * 2 + 1
3 else
1 largeChildIndex = index * 2 + 2
4 end if
4 end if
5 if (heap[index].key < heap[largeChildIndex].key)
1 swap (heap[index], heap[largeChildIndex])
2 rebuildHeap(heap, largeChildIndex, lastIndex)
6 end if
2 end if
and this is my code.. so first I create an array of int and store some random values then I run create heap function which calls rebuildHeap till heap array is complete.
EDITED, removed the array size..
void rebuildHeap(int heap[], int index, int lastindex) {
int leftkey = 0 ;
int largeChildIndex = 0;
int rightkey = 0;
cout << endl;
if (heap[index*2+1] <= heap[lastindex])
{
leftkey = heap[index*2+1];
cout <<" index : " << index*2+1 << " leftkey " << leftkey << endl;
cout <<" index : " << lastindex << " heap[lastindex] = " << heap[lastindex] << endl;
if ((heap[index * 2+ 2]) > heap[lastindex])
largeChildIndex = (index* 2) +1;
else
{
rightkey = heap[index*2+2];
if (leftkey > rightkey)
largeChildIndex = index * 2 +1;
else
largeChildIndex = index*2+2;
}
}
if (heap[index] < heap[largeChildIndex]) {
swap(heap[index], heap[largeChildIndex]);
rebuildHeap(heap, largeChildIndex, lastindex);
}
}
void swap (int &a, int &b) {
int temp = b;
b = a;
a = temp;
}
int main(int argc, const char * argv[])
{
int a[] = {3, 7, 12, 15, 18, 23, 4, 9, 11, 14, 19, 21};
int length = (sizeof(a)/sizeof(a[0]));
for (int i = length/2-1; i >= 0; i-- ) {
rebuildHeap(a, i, length-1);
cout << " i " << i;
}
for (int i = 0; i < length; i++) {
cout << endl<< a[i] << endl;
}
};

First of all I would like to highlight that your translation of the pseudocode was wrong, so I fixed it.
#include <iostream>
using namespace std;
void rebuildHeap(int *heap, int index, int lastindex)
{
int leftkey = 0 ;
int largeChildIndex = 0;
int rightkey = 0;
if ((index*2 + 1) <= lastindex)
{
leftkey = heap[index*2+1];
if ((index*2 + 2) > lastindex)
largeChildIndex = index*2 +1;
else
{
rightkey = heap[index*2+2];
if (leftkey > rightkey)
largeChildIndex = index*2+1;
else
largeChildIndex = index*2+2;
}
}
else
{
return;
}
if (heap[index] < heap[largeChildIndex]) {
swap(heap[index], heap[largeChildIndex]);
rebuildHeap(heap, largeChildIndex, lastindex);
}
}
void swap (int &a, int &b) {
int temp = b;
b = a;
a = temp;
}
int main(int argc, const char * argv[])
{
int a[] = {3, 7, 12, 15, 18, 23, 4, 9, 11, 14, 19, 21};
int length = sizeof(a)/sizeof(a[0]);
//create heap
for (int i = (length/2-1); i >= 0; i --)
{
rebuildHeap(a, i, length-1);
}
//prints the heap array
for (int i = 0; i < length; i++) {
cout << a[i] << " ";
}
return 0;
}
Here is the output: 23 19 21 15 18 12 4 9 11 14 7 3
My understanding of heap is like 0 so I'm not sure what is your expected output.

Related

How to make that equal values in array will be written inside brackets?

I'm new at C++ and I'm trying to solve this problem. Here is the code.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int my_rand_arr(int a, int b);
void random_arr(int arr[], int n);
void output_arr(int arr[], int n);
int main(){
srand(time(0));
const int N = 20;
int arr[N];
random_arr(arr, N);
output_arr(arr, N);
return 0;
}
int my_rand_arr(int a, int b){
return rand() % (b - a + 1) + a;
}
void random_arr(int arr[], int n){
for(int i = 0; i < n; i++){
arr[i] = my_rand_arr(1, 6);
}
}
void output_arr(int arr[], int n){
for(int i = 0; i < n; i++){
if(arr[i] == arr[i + 1]){
cout << "(";
}
cout << arr[i] << " ";
}
cout << endl;
}
It is random array and the thing I'm trying to achieve is that if there is a couple of equal adjacent numbers, those numbers will be written inside brackets.
Expected output:
1 6 3 (1 1) 6 2 (4 4 4) 3 6 1 5 6 5 2 1 (5 5)
What should I do in order to achieve that output?
Just count the number of repetitons of each element and print the elements when reaching the a different element or the end of the array.
void output_arr(int arr[], size_t const n) {
auto pos = arr;
auto const end = arr + n;
while (pos != end)
{
size_t count = 1;
auto const element = *pos;
for (++pos; pos != end && *pos == element; ++pos, ++count)
{
}
if (count == 1)
{
std::cout << element << ' ';
}
else
{
std::cout << '(' << element;
for (; count != 1; --count)
{
std::cout << ' ' << element;
}
std::cout << ") ";
}
}
std::cout << '\n';
}
int main() {
int arr[] = { 1, 6, 3, 1, 1, 6, 2, 4, 4, 4, 3, 6, 1, 5, 6, 5, 2, 1, 5, 5 };
output_arr(arr, sizeof(arr) / sizeof(*arr));
}
Before evaluating the expression arr[i] == arr[i + 1], you must verify that n + 1 is not out of bounds of the array. Otherwise your program will invoke undefined behavior.
Here is my solution to the problem:
#include <iostream>
void output_arr( int arr[], int n )
{
for ( int i = 0; i < n; i++ )
{
//determine whether there are adjacent identical numbers
if ( i + 1 != n && arr[i] == arr[i+1] )
{
//only add space if we are not at the start of the line
if ( i != 0 )
std::cout << ' ';
//print opening parenthesis and first number of repetition
std::cout << '(' << arr[i];
//print remaining numbers of repetition
do
{
i++;
std::cout << ' ' << arr[i];
} while ( i + 1 != n && arr[i] == arr[i+1] );
//print closing parenthesis
std::cout << ')';
}
else
{
//only add space if we are not at the start of the line
if ( i != 0 )
std::cout << ' ';
//print non-repeating number without parentheses
std::cout << arr[i];
}
}
//finish line
std::cout << '\n';
}
int main()
{
int arr[] = { 1, 6, 3, 1, 1, 6, 2, 4, 4, 4, 3, 6, 1, 5, 6, 5, 2, 1, 5, 5 };
output_arr( arr, sizeof arr / sizeof *arr );
}
This program has the desired output:
1 6 3 (1 1) 6 2 (4 4 4) 3 6 1 5 6 5 2 1 (5 5)

How to get the longest sequence of prime numbers from an array in c++

I'm trying to get the longest(largest) sequence of consecutive prime numbers from an array..
On first test with 10 elements in the array works , but when i tried with 15 elements like: 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 it spit out 4, which is incorrect.
#include <iostream>
using namespace std;
int main()
{
int bar[100];
int x, j = 0;
int maxseq = 0;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
for (int i = 1; i < x - 1; i = j) {
int startseq = i;
int seq = 0;
j = i + 1;
bool prim = true;
int a = bar[i];
for (int d = 2; d <= a / 2; d++) {
if (a % d == 0) {
prim = false;
}
}
while (j < x && prim) {
seq++;
if (seq > maxseq) {
maxseq = seq;
longestseqstart = i;
}
int a = bar[j];
for (int d = 2; d <= a / 2; d++) {
if (a % d == 0) {
prim = false;
}
}
j++;
}
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
I would write the program the following way
#include <iostream>
#include <iterator>
#include <algorithm>
bool is_prime( unsigned int n )
{
bool prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main()
{
unsigned int a[] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t maxseq = 0;
for ( auto current = std::find_if( a, a + N, is_prime );
current != a + N;
current = std::find_if( current, a + N, is_prime ) )
{
auto first = current;
current = std::find_if_not( current, a + N, is_prime );
size_t n = std::distance( first, current );
if ( maxseq < n ) maxseq = n;
}
std::cout << "The longest sequence is: " << maxseq << '\n';
return 0;
}
The program output is
The longest sequence is: 5
I did not use generic functions std::begin( a ) and std::end( a ) because in your program the array can contain less actual elements than the array dimension.
If you do not know yet standard C++ algorithms then the program can be defined the following way
#include <iostream>
bool is_prime( unsigned int n )
{
bool prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main()
{
unsigned int a[] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t maxseq = 0;
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
bool prime = a[i] % 2 == 0 ? a[i] == 2 : a[i] != 1;
for ( unsigned int j = 3; prime && j <= a[i] / j; j += 2 )
{
prime = a[i] % j != 0;
}
if ( prime )
{
if ( maxseq < ++n ) maxseq = n;
}
else
{
n = 0;
}
}
std::cout << "The longest sequence is: " << maxseq << '\n';
return 0;
}
The program output is the same as above
The longest sequence is: 5
As for your program then this loop
for (int i = 1; i < x - 1; i = j) {
skips the first element of the array that is bar[0].
And due to this statement
j = i + 1;
the calculated value of seq one less than it should be because you do not take into account that bar[i] is already prime.
Set initially seq equal to 1.
int seq = 1;
Moreover you incorrectly are determining prime numbers. For example according to your algorithm 1 is prime.
You are checking twice for prime numbers and you are using a nested loop. That's not necessary. It's enough to read all numbers, check each number, increment the count if it's a prime number and store the maximum sequence length.
#include <iostream>
#include <vector>
using namespace std;
bool isPrime(int a) {
bool prim = true;
for (int d = 2; d*d <= a; ++d) {
if (a % d == 0) {
prim = false;
}
}
return prim;
}
int main()
{
int x;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
std::vector<int> bar(x);
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
unsigned int count = 0;
unsigned int maxseq = 0;
for (const auto &el : bar) {
if (isPrime(el)) {
++count;
if (count > maxseq) maxseq = count;
} else count = 0;
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
Of course you can avoid the usage of std::vector and functions with
#include <iostream>
using namespace std;
int main()
{
int x;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
int bar[100];
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
unsigned int count = 0;
unsigned int maxseq = 0;
for (unsigned int i = 0; i < x; ++i) {
int a = bar[i];
bool prim = true;
for (int d = 2; d*d <= a; ++d) {
if (a % d == 0) {
prim = false;
}
}
if (prim) {
++count;
if (count > maxseq) maxseq = count;
} else count = 0;
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
The algorithm looks basically OK. The issue is mostly one of organization: the way the inner loop block is set up means that a run of primes will be short by 1 because the longest sequence is only updated at the beginning of the inner loop, missing the final prime.
A couple of minimal failing examples are:
How big is the array? =1
bar[0]=13
The longest sequence is: 0
How big is the array? =2
bar[0]=5
bar[1]=6
The longest sequence is: 0
Note that there's a repeated prime check in two places. This should not be. If we move all of the prime logic into the loop and test for a new longest sequence only after finishing the entire run, we'll have a clear, accurate algorithm:
#include <iostream>
int is_prime(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int nums[100];
int n;
std::cout << "How big is the array? =";
std::cin >> n;
for (int i = 0; i < n; i++) {
std::cout << "nums[" << i << "]=";
std::cin >> nums[i];
}
int longest = 0;
for (int i = 0, start = 0; i < n; i++) {
for (start = i; i < n && is_prime(nums[i]); i++);
longest = std::max(longest, i - start);
}
std::cout << "The longest sequence is: " << longest;
return 0;
}
In this rewrite I...
avoided using namespace std;.
removed unnecessary/confusing variables.
used clear variable names (bar should only be used in example code when the name doesn't matter).
moved is_prime to its own function.
But there are outstanding issues with this code. It should...
use a vector instead of an array. As it stands, it's vulnerable to a buffer overflow attack should the user specify an array length > 100.
use a faster method of finding primes. We only need to check up to the square root of the number and can skip a lot of numbers such as even numbers after 2. I suspect this is incidental to this exercise but it's worth mentioning.
move the longest_prime_sequence to a separate function (and possibly user input gathering as well).
Convert the array to a Boolean array and find longest length. Try this snippet(not optimized):
bool is_prime(int n) {
for (int i = 2; i < n; i++) {
if (n%i == 0) return false;
}
return true;
}
int main() {
//Input
unsigned int bar[15] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
// Convert input to boolean array
bool boo[15];
for (int i = 0; i < 15; i++) {
boo[i] = is_prime(bar[i]);
}
//Check the longest boolean array
int longest = 0;
for (int i = 0; i < 15; i++) {
int count = 0;
while (boo[i + count] && (i+ count) <15) {
count++;
}
if (longest < count) longest = count;
}
//Output
cout << longest;
return 0;
}

Comparing double in C++

I have written the following program intended on comparing float's in C++. Originally this was written trying to compare double's but I soon realized how bad a problem that is. In general what is supposed to happen is that the program is to compare the two numbers of the given slot array and swap them as necessary.
#include<iostream>
using namespace std;
int swap(float[] , int, int);
int main() {
float slot[10] = {8.25, 3.26, 1.20, 5.15, 7.99, 10.59, 4.36, 9.76, 6.29, 2.09};
int n=10, i;
int lower, upper, sortflag, sml, scan;
lower = 0;
upper = n-1;
sortflag = 1;
float temp;
while( (lower < upper) && (sortflag == 1)) {
sml = lower;
sortflag = 0;
scan = lower + 1;
while(scan <= upper - lower) {
if (slot[scan] > slot[scan + 1]) {
swap(slot, scan, scan + 1);
sortflag = 1;
if(slot[scan] < slot[sml]) sml = scan;
}
scan++;
}
swap(slot, lower, sml);
upper = upper - 1;
lower = lower + 1;
}
cout << "AFTER SORT: " << endl;
for (i= 0; i < n; i++) cout << slot[i] << " ";
cout << endl;
return 0;
}
void swap(float data[], int i, int j) {
float temp;
temp = data[i];
data[j] = data[i];
data[j] = temp;
}
When I ran this program with double instead of float, the program ran infinitely until I had to invoke Ctrl+C to break it. After switching to float I instead get the following output:
AFTER SORT:
8.25 8.25 3.26 5.15 7.99 10.59 10.59 10.59 10.59 10.59
0 0 1 3 4 5 5 5 5 5
--------------------------------
Process exited after 0.06651 seconds with return value 0
Press any key to continue . . .
Where is the logic going wrong?
EDIT: So after some consideration, I went ahead and rewrote the program to make it compare int array values instead.
int slot[10] = {8, 3, 1, 5, 7, 10, 4, 9, 6, 2};
And adjusted all the appropriate functions as necessary:
// Declaration of function:
void swap(int[] , int, int);
void swap(int data[], int i, int j) {
int temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
And the function is now coming up correct with the correct input. There is no problems with going out of bounds here.
AFTER SORT:
1 2 3 4 5 6 7 8 9 10
--------------------------------
Process exited after 0.05111 seconds with return value 0
Press any key to continue . . .
Here's the new modified program:
int main() {
int slot[10] = {8, 3, 1, 5, 7, 10, 4, 9, 6, 2};
int n=10, i;
int lower, upper, sortflag, sml, scan;
lower = 0;
upper = n-1;
sortflag = 1;
while( (lower < upper) && (sortflag == 1)) {
sml = lower;
sortflag = 0;
scan = lower + 1;
while(scan <= (upper-lower)) {
if (slot[scan] > slot[scan + 1]) {
swap(slot, scan, scan + 1);
sortflag = 1;
if(slot[scan] < slot[sml]) sml = scan;
}
scan++;
}
swap(slot, lower, sml);
upper = upper - 1;
lower = lower + 1;
}
cout << "AFTER SORT: " << endl;
for (i= 0; i < n; i++) cout << slot[i] << " ";
cout << endl;
//for (i= 0; i < n; i++) cout << index[i] << " ";
cout << endl;
return 0;
}
void swap(int data[], int i, int j) {
int temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
So now the question is why does the int version work without problem but neither the double nor float versions do?
Your swap function is wrong. data[j] = data[i]; is useless when followed by another write data[j] = temp;. It should be like this
int swap(float data[], int i, int j) {
float temp;
temp = data[i];
data[i] = data[j]; // reverse this line
data[j] = temp;
return 0;
}
And there's no point making the function returning int if you don't use the result. Just declare it void

Solving a simple matrix in row-reduced form in C++

Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce (float A[][4]);
int main() {
// answer should be { 2, 4, -3 }
float A[3][4] = {
{ 5, -6, -7, 7 },
{ 3, -2, 5, -17 },
{ 2, 4, -3, 29 }
};
printmatrix(A);
RowReduce(A);
}
// Outputs the matrix
void printmatrix(float A[][4]) {
int p = 3;
int q = 4;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
void RowReduce (float A[][4]){
//rows
int p = 3;
//columns
int q = 4;
// the determines the column we are at which holds the diagonal,
// the basis for all elimination above and below
int lead = 0;
cout << endl;
while ( lead < q - 1 ) {
// for each row . . .
for (int i = 0; i < p; i++) {
// ignore the diagonal, and we will not have a tree rref
// as the diagonal will not be divided by itself. I can fix that.
if ( i != lead ) {
cout << A[lead][lead] << " " << A[i][lead];
for (int j = 0; j < q; j++) {
//here is the math . . . . probably where the problem is?
A[i][j] = A[lead][lead] * A[i][j];
A[i][lead] = A[i][lead] * A[lead][j];
A[i][j] = A[i][j] - A[i][lead];
}
cout << endl;
}
}
// now go to the next pivot
lead++;
cout << endl;
}
}
I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!
The main error in you code is that you are calculating the divisor or multiplier within the for loop. You should calculate them before iterating over the cells.
Hint: debugging is easier if the code is well formated and the variables have meaningful names.
See the implementation of RowReduce():
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce(float A[][4]);
int main()
{
float A[3][4] = {{5, -6, -7, 7},
{3, -2, 5, -17},
{2, 4, -3, 29}}; //answer should be {2, 4, -3}
printmatrix(A);
RowReduce(A);
}
void printmatrix(float A[][4]) // Outputs the matrix
{
int p=3;
int q=4;
for (int i=0; i<p; i++) {
for (int j=0; j<q; j++) {
cout << setw(7) << setprecision(4) << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void RowReduce(float A[][4])
{
const int nrows = 3; // number of rows
const int ncols = 4; // number of columns
int lead = 0;
while (lead < nrows) {
float d, m;
for (int r = 0; r < nrows; r++) { // for each row ...
/* calculate divisor and multiplier */
d = A[lead][lead];
m = A[r][lead] / A[lead][lead];
for (int c = 0; c < ncols; c++) { // for each column ...
if (r == lead)
A[r][c] /= d; // make pivot = 1
else
A[r][c] -= A[lead][c] * m; // make other = 0
}
}
lead++;
printmatrix(A);
}
}
The output:
5 -6 -7 7
3 -2 5 -17
2 4 -3 29
1 -1.2 -1.4 1.4
0 1.6 9.2 -21.2
0 6.4 -0.2 26.2
1 0 5.5 -14.5
0 1 5.75 -13.25
0 0 -37 111
1 0 0 2
0 1 0 4
0 0 1 -3

C++ Finding local maxima in 2d array

I am trying to write a program that finds and prints all the local maxima in this 2D array, looking at the 2nd column only. Think I am on the right track but don't know how to proceed and it doesn't give the correct output. Thanks.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localmax = array[i][1];
Index = i;
}
}
cout << "The local maxima in the array are " << localmax << endl;
cout << "The corresponding values in the array are " << array[Index][0] << endl;
_getch();
return 0;
}
You are overwriting your (single) float localmax.
There are two solutions to your problem:
Nr. 1: You could print localmax everytime you find one (put the cout in the for loop)
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localmax = array[i][1];
cout << "A local maxima is: " << localmax << endl;
Index = i;
}
}
_getch();
return 0;
}
Nr. 2: You create a localmax vector and use push_back to save any local maxima you find.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
std::vector<float> localMaxVector;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localMaxVector.push_back(array[i][1]);
Index = i;
}
}
cout << "The local maxima in the array are " << endl;
for( std::vector<float>::const_iterator i = localMaxVector.begin(); i != localMaxVector.end(); ++i)
std::cout << *i << ' ';
_getch();
return 0;
}
You don't verify the array index before setting "before" and "after", I'm surprised your code didn't crash (i-1 and i+1).
I don't have much time so I haven't tried it, but it should work.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, { 6, 19 }, { 7, 12 } };
int i;
float before = 0, after = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if (i > 0)
{
before = array[i-1][1];
}
if (i < 6)
{
after = array[i+1][1];
}
if ((i == 0 || array[i][1] >= before) && (i == 6 or array[i][1] >= after))
{
//when you're at the very first point, you don't have to verify the 'before' variable, and for the very last point, you don't have to verify 'after'
cout << array[i][1] << " at position " << i << " is a maxima" << endl;
}
}
_getch();
return 0;
}
If you want to keep the results, you can use the std::vector like Thomas.
I don't think your loop is correct. If you inserted an element {0, 20} at the start of your array, your code would return 19 and 22 (assuming 'before' remains at 0 when i == 0). I expect you want 22, 16, 19. If so, your loop should look like this:
for (i = 0; i<7; i++)
{
if ((i == 0 || array[i][1] > array[i - 1][1]) && (i == 6 || array[i][1] >= array[i + 1][1]))
{
localmax = array[i][1];
Index = i;
}
}