Find the index of the minimum element in a subarray - c++

The function FindSubArrayMinimum is suppose to return the index of the minimum value in an array between the values (left,right). Instead of returning 1 as it should, it returns 7.
Here is my code:
#include <iostream>
using namespace std;
class Minimum {
int *array;
int arrayLen;
public:
Minimum(int *array, int arrayLen) {
}
void swap(int &a, int &b) {
int x;
x = a;
a = b;
b = x;
}
int findMinimum(int a, int b) {
if(a < b){
return a;
}else{
return b;
}
}
int findArrayMinimum(int a[], int arraySize) {
int min=a[0];
for(int i=0;i<arraySize-1;i++){
if(a[i] < min){
min = i;
}
}
return min;
}
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
cout << min << endl;
min = i;
}
}
return min;
}
int findSubArrayMinimumAndSwap(int left, int right, int swapIndex) {
}
};
int main() {
int A[5] = {47, 7, 21, -1, 11};
Minimum min(A, 5);
cout << "Minimum of 7 and 11 is " << min.findMinimum(7, 11) << endl;
int x = 5, y = 7;
min.swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
cout << "Minimum value is at position " << min.findArrayMinimum(A,5) << endl;
cout << "Minimum value between [1,2] is at position " <<
min.findSubArrayMinimum(A,5,1,2)<< endl;
return 0;
}
I cannot for the life of me figure out why it won't return the minimum index. Logically speaking it should work unless I'm missing something?

all of my other functions as all the ones I have finished I have working.
It is not true. In findArrayMinimum the loop should be
for(int i=0;i<arraySize;i++)
Or
for(int i=0;i<=arraySize-1;i++)
The initial value an the condition in the loop are also wrong. Should be int min=0 and if(a[i] < a[min])
Instead of returning 1 as it should, it returns 7.
findSubArrayMinimum is nice, except initial minimum value int min = a[left], should be int min = left and the condition in the loop should be if(a[i] < a[min]).
arraySize is odd in findSubArrayMinimum, it is not used.
Your do not need the separate implementation for findSubArray. You can do return findSubArrayMinimum(a, 0, arraySize - 1) in findSubArray.
If you would implement the tests with arrays of 0, 1, many elements, with the left, right, middle subarrays, you would discover all bugs in your code.

C++ is all about not re-inventing wheels.
#include <algorithm>
size_t findArrayMinimum(int a[], size_t arraySize) {
// Returns index of minimum element
return std::min_element(a, a + arraySize) - a;
}

In your findSubArrayMinumum you need min = a[i]; and not min = i; i is a index and a[i] is value.
I suggested you:
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int index = left;
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
min = a[min];
index = i;
}
}
return index;
}
int index = min.findSubArrayMinimum(A,5,1,3);
cout << "Minimum value between [1,2] is at position " << index <<
". and value is: " << A[index] << endl;

int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
//The min is the index of minimum value since you are returning the index only
int min = left;
for(int i=left;i<=right;i++){
//since we have min = indexOfMin, then we need to compare the values
if(a[i] <= a[min]){
min = i;
}
}
//remember! You are returning the index of the minmum value!
return min;
}

Related

Dynamic allocation of an array into a function with pointer parameters

I am having issues finishing passing an array via pointers through a series of functions. I create a function using dynamic allocation to create it. Even though that is successful I cannot get it to pass through functions that take pointers as arguments. The functions return the mean median and mode and have been completed. However I cannot pass them when converting them into pointer syntax. Thanks for the help in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
int students;
int * studentarray;
int stumode;
double stuavg;
int stumed;
int arr;
int mode(int *[], int );
double average(int *[], int);
double median(int *[], int);
void selectSort(int [], int);
void swap(int *, int *);
int makeArray(int*, int);
int main()
{
studentarray = &arr;
cout << "How many students are there?" << endl;
cin >> students;
makeArray(studentarray, students);
for (int i = 0; i < students; i++) {
cout << "How many movies did student " << i + 1 << " view?" << endl;
cin >> studentarray[i];
}
selectSort(studentarray, students);
stumode = mode(&studentarray, students);
stuavg = average(&studentarray, students);
stumed = median(&studentarray, students);
cout << "The array has been sorted in ascending order." << endl;
cout << "The mode is " << stumode << "." << endl;
cout << "The mean is " << stuavg << "." << endl;
cout << "The median is " << stumed << "." << endl;
delete[] studentarray;
return 0;
}
int mode(int *arr, int size)
{
if (size <= 0) return 0;
int most = 0, position = 0, most_count = 0;
int counter = 1;
for (int i = 1; i < size; i++)
{
if (* (arr + i) != * (arr + position) )
{
if (counter > most)
{
most = counter;
most_count = 0;
}
else if (counter == most) most_count++;
position = i;
counter = 0;
}
else counter++;
}
if (most_count) return 0;
else return * ( arr + position );
}
double average(int *arr, int size)
{
if (size <= 0) return 0;
int total = 0;
for (int i = 0; i < size; i++) {
total += *(arr + i);
}
return (double)total / size;
}
double median(int *arr, int size)
{
if (size <= 0) return 0;
if (size % 2 == 0)
return (double) (* (arr + (size + 1) / 2));
else {
int mid = size / 2;
return (double)(* (arr + mid) + * (arr + mid + 1) / 2);
}
return 0;
}
void selectSort(int arr[], int size)
{
int min;
for (int i = 0; i < size - 1; i++)
{
min = i;
for (int j = i + 1; j < size; j++)
{
if ( arr[j] < arr[min])
{
min = j;
}
}
swap(&arr[min], &arr[i]);
}
}
void swap(int *one, int *two) {
int temp = *one;
*one = *two;
*two = temp;
}
int makeArray(int *arr, int size)
{
arr = new int[size];
return *arr;
}
Your implementation of makeArray is not right.
int makeArray(int *arr, int size)
{
// Allocates memory and assigns it to arr.
// This is a local change to arr. The value of the variable in
// main remains unchanged.
arr = new int[size];
// Returns an uninitialized value.
return *arr;
// The memory allocated in the previous line is now a memory leak.
}
You can make it simpler by using:
int* makeArray(int size)
{
return new int[size];
}
and use it in main as:
arr = makeArray(students);
However, I don't see how that is better than using:
arr = new int[students];
If you do that, makeArray becomes unnecessary. If makeArray needs to have additional code to fill up the array with some values, it will be useful. Otherwise, it does not add any useful functionality to your program.
Having said all of that, it is better to use std::vector instead of managing dynamically allocated memory in your own code. You would use:
std::vector<int> arr(students);
PS
I did not go through rest of your code. There might be other errors.

Problems with Indexing Minimum value from array using a function

So we were given a project involving two arrays (one a string and the other including values), and I decided to use movies and years. One of the parameters of the project is to display the maximum and minimum values along with their string. Now, the max works fine, but when I try to run min, it says it isn't initialized. What am I doing wrong?
#include <iostream>
#include <string>
using namespace std;
int avgYear(int arr[], int size);
int indexMin(int arr[], int size);
int indexMax(int arr[], int size);
int main()
{
int total = 0;
string name[] = {"Toy Story", "A Bug's Life", "Toy Story 2", "Monster's Inc.", "Finding Nemo", "The Incredibles", "Cars", "Ratatouille", "WALL-E", "Up"};
int year[] = { 1995, 1998, 1999, 2001, 2003, 2004, 2006, 2007, 2008, 2009};
for (int x = 0; x < 10; x++)
cout << name[x] << " " << year[x] << endl;
cout << "The average year of release was " << avgYear(year, 10) << endl;
cout << "The First Year of Release was " << name[indexMin(year, 10)] << " in " << year[indexMin(year, 10)] << endl;
cout << "The Last Year of Release was "<< name[indexMax(year, 10)] << " in " << year[indexMax(year, 10)] << endl;
return 0;
}
int avgYear(int arr[], int size)
{
int avg;
int total=0;
for (int x = 0; x < size; x++)
total += arr[x];
avg = total / size;
return avg;
}
int indexMin(int arr[], int size)
{
int iMin;
int min = arr[0];
for (int x = 1; x < size; x++)
if (arr[x] < min)
{
min = arr[0];
iMin = x;
}
return iMin;
}
int indexMax(int arr[], int size)
{
int iMax;
int max = arr[0];
for (int x = 0; x < size; x++)
if (arr[x] > max)
{
max = arr[x];
iMax = x;
}
return iMax;
}
If minimum value is arr[0] then iMin won't ever be initialized because if (arr[x] < min) will never return true.
You max function also has the same problem but works because max element is not at index 0.
int iMin = 0;
Should fix your problem. Also it's a good idea to develop a habit to always initialize your variables and fields. Value stored in an uninitialized variable is indeterminate, reading from it is undefined behaviour.
if you initialize years like this:
int year[] = { 2009, 2008, 2007, 2006, 2004, 2003, 2001, 1999, 1998, 1995};
and then, the min work fine, and the max is error.^_^
you must initialize the iMin and iMax, and the initial number need to be the same with arr index, like this:
// min
int nStartIndex = 0;
int iMin = nStartIndex;
int min = arr[nStartIndex];
// max
int nStartIndex = 0;
int iMax = nStartIndex;
int max = arr[nStartIndex];

Array element number

I need some help with a simple program. And no - its not my homework (I am learning Cpp for myself and maybe use it in future)
So yeah. I have a program, that reads arrays size 10, and then put numbers in it {2.56, 1.598, 0, 5.15, 0, 3.012, 10, 4.789, 2.569, 0}
The program should ignore the 0, and it does, but the problem is.. I need to get the number of the where the number is placed in array
(Smallest number is 1.598 and its 2 in the array)
Meanwhile I get number 8 on the biggest (should be 5 if zeros would be ignored)
and 1 on the smallest. How can I fix that ?
Heres the void of the biggest number :
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0]
for (int i = 1; i < n; i++){
if (array[i] == 0)
continue;
if (array[i] > max){
max = array[i];
maxNr = i;
}
}
}
Printing void :
void Print(float min, float max, double avg, int maxNr, int minNr)
{
ofstream info;
info.open("result1.txt");
info << "Biggest: " << max << " Number : " << maxNr << endl;
info << "Smallest: " << min << " Number : " << minNr << endl;
info << "Average: " << avg << endl;
info.close();
}
And all main.
int main(){
float array[100];
int n;
float max;
float min;
double avg;
int maxNr, minNr;
Reading(array, n);
Biggest(array, n, max, maxNr);
Smallest(array, n, min, minNr);
Average(array, n, avg);
Printing(min, max, avg, maxNr, minNr);
return 0;
}
First of all, array indexes start at 0, not 1.
If you want to get the position ignoreing zeros, you need to use a separate counter variable from the one used to index the array, so that you don't increment it when you skip over 0.
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0];
int position = 0;
for (int i = 0; i < n; i++){
if (array[i] == 0) {
continue;
}
if (array[i] > max){
max = array[i];
}
position++;
}
maxNr = position;
}
Arrays in most (all that I can think of) programming languages start at index zero. So simply change your for loop condition to be:
for (int i = 0; i < n; i++)
Because you want the loop to start at the first element in the array, i must be initialized to 0. That should fix the problem you are having with the array.

C++ Program To Find Smallest and Largest Number In Array

Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001

Array sorting, Array input, Array Output

I'm having some problems with this program. It is meant to input random numbers into an array, change its dimensions, sort them, the output the sorted array. For some reason, the array will only fill with one number (-858993460) and I cannot figure out why. Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstring>
using namespace std;
void InputArray(int[][5], int, int);
void OutputArray(int[], int);
void SelectionSort(int[], int);
void CopyArray(int[][5], int, int, int[], int);
int main()
{
int sample_1[80];
int sample_2[16][5];
InputArray(sample_2, 16, 5);
CopyArray(sample_2, 16, 5, sample_1, 80);
cout << "Before sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
SelectionSort(sample_1, 80);
cout << "After sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
return 0;
}
//generate random numbers for a two dimensional array
void InputArray(int array[][5], int m, int n)
{
int i, j;
srand(time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
array[i][j] = rand() % 1000;
}
}
}
//display values in a one-dimensional array
void OutputArray(int array[], int number)
{
int i;
for (i = 0; i < number; i++)
{
cout << array[i] << "\t";
}
}
// selection sort of a one-dimensional array
void SelectionSort(int numbers[], int array_size)
{
int i, j, a;
for (i = 0; i < array_size; ++i) {
for (j = i + 1; j < array_size; ++j) {
if (numbers[i] > numbers[j]) {
a = numbers[i];
numbers[i] = numbers[j];
numbers[j] = a;
}
}
}
return;
}
//x and y and two dimensions of array_2d; n is the dimension of array_1d
//copy values from array_2d[][] to array_1d[]
//assume x*y equals n
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
return;
}
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
}
That's your problem right there. The size of the array_1d is unspecified here. The sizeof() operator does not know the size of the array that's being copied.
In fact, I'm surprised that this even compiles, although I'm too lazy to test it with gcc.
What you need to do is calculate the size of the array yourself, multiply it by sizeof(int), and use that instead of the existing sizeof() operator.