How to input array here? i.e the user has to give the 5 values for arr[] instead of arr[] = (0, -1, 2, -3, 4} . If I give arr[] it shows error. I'm a begginer so please help me.
using namespace std; // function to print triplets with 0 sum
void findTriplets(int arr[], int n)
{
bool found = false;
for (int i=0; i<n-1; i++)
{
// Find all pairs with sum equals to
// "-arr[i]"
unordered_set<int> s;
for (int j=i+1; j<n; j++)
{
int x = -(arr[i] + arr[j]);
if (s.find(x) != s.end())
{
printf("%d %d %d\n", x, arr[i], arr[j]);
found = true;
}
else
s.insert(arr[j]);
}
}
if (found == false)
cout << " No Triplet Found" << endl; }
int main()
{
int arr[] = {0, -1, 2, -3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0; }
The simplest way is to get n from user and cin arr in a loop:
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
findTriplets(arr, n);
If you don't want to pass the size of array you can use std::vector instead of array, and the push_back() method;
Related
I'm doing a program that finds the max value in a array. I done it but I found a strange bug.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 1; i <= n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
} cout << max_value;
return 0;
}
When I put 5 as first line for the number of elements and 2, 7, 6, 8, 9 as the elements of the array. It returns 16 instead of 9. Please help
In Arrays the first index starts with 0 and ends in n - 1 assuming the array is of length n
so when looping from i = 1 to i <= n. n is now larger than n - 1.
the solution would be to start from 0 and end at i < n hence:
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
}
cout << max_value;
return 0;
}
you could also use the std::max function like so:
for(int i = 0; i < n; i ++) {
max_value = max(max_value, arr[i]);
}
The other posts already pointed out problem in your code.
You should be aware of that int arr[n]; is not permitted in standard C++.
[GCC and CLANG compiler support it in C++ as an extension]
An alternative is to allocate memory dynamically:
int *arr = new int[n];
and to find maximum value you can use std::max_element:
int max_value = *(std::max_element(arr, arr + n));
Instead of dynamic array, its better to use vector STL (make yourself familiar with Containers Library). You can do:
std::vector <int> arr;
for (int i = 0; i < n; i++) {
int input;
std::cin >> input;
arr.push_back(input);
}
int max_value = *std::max_element(arr.begin(), arr.end());
std::cout << "Max element is :" << max_value << std::endl;
in your second for do this
for (int i = 1; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
delete '=' from i <= n because i is index which start from 0
and instead of this
int arr[n];
do this
int *arr = new int[n];
I'm new to c++ and i'm having a problem with my code. I need to show the original indexes of a vector before it was sorted, after sorted. I tried it like this:
#include <vector>
using namespace std;
void bubblesort(vector<int> &a, int n) {
for (int j = 0; j < n - 1; j++) {
for (int i = n - 1; i > j; i--) {
if (a.at(i) < a.at(i-1)) {
int aux = a.at(i);
a.at(i) = a.at(i-1);
a.at(i-1) = aux;
}
}
}
}
int main()
{
int n;
cout << "Digite o tamanho do vetor: ";
cin >> n;
vector<int> v;
vector<int> vold;
vector<int> pos;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
vold.push_back(a);
}
bubblesort(v, n);
for (int i = 0; i < n; i++) {
if (vold.at(i) == v.at(i)) {
pos.push_back(i);
}
else {
for (int j = i+1; j < n - 1; j++) {
if (vold.at(i) == v.at(j)) {
pos.at(j) = i;
break;
}
}
}
}
for (const int& i : pos) {
cout << i << " ";
}
system("pause>0");
}
But it didn't worked, if someone could help me to see what I'm doing wrong I would be glad, thanks in advance.
If your goal is to show the indices of the sorted vector, then another approach is to not sort the original vector, but instead to sort a vector of index values based on the original vector.
The index vector would be initialized to 0, 1, 2, etc. up until the vector's size, minus 1.
Here is an example:
#include <vector>
#include <numeric>
#include <iostream>
void bubblesort(std::vector<int> &a, std::vector<int>& index)
{
// Make sure the index vector is the same size as
// the original
index.resize(a.size());
if ( a.size() <= 1 )
return;
// This is just a shortcut way of setting the values to 0,1,2,etc.
std::iota(index.begin(), index.end(), 0);
size_t n = a.size();
// Here is your sort, but with one difference...
for (size_t j = 0; j < n - 1; j++)
{
for (size_t i = n - 1; i > j; i--)
{
// Look at the comparison being done here using the index array
if (a.at(index[i]) < a.at(index[i-1]))
{
// We swap the index values, not the values
// in the vector
int aux = index.at(i);
index.at(i) = index.at(i-1);
index.at(i-1) = aux;
}
}
}
}
int main()
{
std::vector<int> v = {3, 1, 65, 23, 4};
std::vector<int> index;
bubblesort(v, index);
// Display the index values of the sorted items
for (const int& i : index)
std::cout << i << " ";
}
Output:
1 0 4 3 2
Note that the bubblesort function takes a vector of indices, and not n. There is no need to pass n, since a vector already knows its own size by utilizing the size() function.
The output shows the original index of each of the sorted items.
As array name acts like a pointer to the starting address of the array, so when passed to a function, why the array is not modifying. When I used a static pointer which just storing the address of the array. After that returning the array by using its name is not causing any problem. Why is it so?
#include<iostream>
using namespace std;
int main()
{
int a[10]={2,16,19,20,2,9,18};
int* bubble(int [],int);
cout<<"the sorted array is ";
int n=10;
int *ma=bubble(a,n);
for(int i=0;i<10;i++)
{
cout<<ma[i]<<'\n';
}
return 0;
}
int* bubble(int *a,int n)
{
int no_of_comparisons;
int ptr,temp;
static int *ma=a;
while(no_of_comparisons<=n-1-1)
{
ptr=0;
while(ptr<=n-1-no_of_comparisons-1)
{
if(a[ptr]>a[ptr+1])
{
temp=a[ptr];
a[ptr]=a[ptr+1];
a[ptr+1]=temp;
}
ptr+=1;
}
no_of_comparisons+=1;
}
return a;
}
Bubble sort is the simplest algorithm to implement and the slowest algorithm on very large inputs, by the way. The basic idea is, just to loop through array from i=0 to n and swap adjacent elements if they are out of order. Below I re-wrote your code, so that it is more readable, clear, and short. I hop it helps.
#include<iostream>
int* bubble(int [], int);
int main()
{
int arr[10] = {2, 16, 19, 20, 28, 9, 18, 22, 32,1};
int arr_size = 10;
std::cout << "Original Array: \n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< '\n';
bubble(arr, arr_size);
std::cout << "Sorted Array: \n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< '\n';
return 0;
}
int* bubble(int *a, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = n - 1; j > i; j--)
{
if( a[j] < a[j - 1] )
{
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
return a;
}
The main problem in your code was, first the no_of_comparisons variable were not initialized. In your case, it should be 0 I think.
Given an array, I am trying to find the maximum sub-array sum. A sub-array is as follows. For example, I get the following array: [9, -7, 5, 3, 91]. Whilst [9, -7, 5] is a sub-array, [9, 5, 3, 91] is not. My code is below:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int arraylen, subarraylen, subarraysum, itervar1, itervar2, itervar3, incrementvar;
cin >> arraylen;
vector<int> mainarray(arraylen);
vector<int> sumarray(arraylen * (arraylen-1) + 1);
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
cin >> mainarray[itervar1];
}
sumarray[0] = 0;
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
for (itervar2 = arraylen; itervar2 > 0; itervar2--) {
subarraylen = itervar2-itervar1;
if (subarraylen < 1) {
continue;
}
vector<int> subarray(subarraylen);
incrementvar = 0;
for (itervar3 = itervar1; itervar3 < itervar2; itervar3++) {
subarray[incrementvar] = mainarray[itervar3];
incrementvar++;
}
subarraysum = 0;
for (itervar3 = 0; itervar3 < subarraylen; itervar3++) {
subarraysum += subarray[itervar3];
}
}
}
return 0;
}
For some reason, it doesn't work; just infinitely loops around. Any help would be appreciated.
First, here is a routine to list all the sub arrays:
vector<int> vec{ 9, -7, 5, 3, 91 };
int sz = vec.size();
for(int start = 0; start < sz; start++)
{
for(int end = start; end < sz; end++)
{
for(int j = start; j <= end; j++)
{
cout << vec[j] << ", ";
}
cout << "\n";
}
}
Now you just have to get the total in loop j, add to a vector sum. You don't need to know the size of sum before hand. Use push_back to add total to sum.
Note, the array itself is included as a sub array, you can exclude that array depending on what the definition is.
I've been tinkering around with it for a while now and I'm so close! Now the output seems to be continuously printing a zero as the first value of the "sorted" vector. This is homework on how to create a selection sort in C++.
Example Output
Vector: 6, 2, 11, 1, 12, 4
Sorted Vector: 0, 2, 11, 6, 12, 4
Code
void selectionSort (vector<int>& data)
{
int min, temp, n=data.size(), i, j;
for (i=0; i<n; i++)
{
min = i;
for (j=i+1; j<n; j++)
{
if (data[min]>data[j])
{
min=j;
}
temp=data[min];
data[min]=data[i];
data[i]=temp;
}
return;
}
}
int main()
{
int n;
vector<int> data;
cout<<"Vector length?: "<<endl;
cin>>n;
srand(time(0));
for (int i=0; i<n; i++)
{
data.push_back(rand()%20+1);
}
cout<<"Vector: "<<endl;
for (int i=0; i<n; i++)
{
cout<<data[i]<<" "<<endl;
}
selectionSort(data);
cout<<"Selection Sorted Vector: "<<endl;
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<" "<<endl;
}
system("Pause");
return 0;
}
Consider the following correct implementation of a selection sort and compare it to yours:
#include <iostream>
#include <vector>
void selection_sort(std::vector<int> &numbers)
{
// Iterate through all possible start indices.
for (int i = 0; i < numbers.size(); ++i)
{
// Determine the index of the minimum for this iteration.
int index_of_min = i;
for (int j = i; j < numbers.size(); ++j)
{
if (numbers[j] < numbers[index_of_min])
{
index_of_min = j;
}
}
// Swap the minimum element with the element at the start index.
int temp = numbers[i];
numbers[i] = numbers[index_of_min];
numbers[index_of_min] = temp;
}
}
int main()
{
std::vector<int> numbers = { 20, 17, 13, 12, 25 };
selection_sort(numbers);
for (size_t i = 0; i < numbers.size(); ++i)
{
std::cout << numbers[i] << " ";
}
}
Given an array of n elements, a selection sort performs n swaps.
You're performing far more swaps than that.
You also have an unexpectedly early call to return.
Let's look at a proper implementation of the sort:
#include <iostream>
#include <vector>
using namespace std;
void selectionSort (vector<int>& data)
{
const int n = data.size();
for (int i=0; i<n; i++)
{
int min = i;
for (int j=i+1; j<n; j++)
if (data[min]>data[j])
min = j;
swap(data[min], data[i]);
}
}
int main() {
vector<int> data = {6, 2, 11, 1, 12, 4};
selectionSort(data);
for (auto element : data)
cout << element << " ";
cout << "\n";
}
Which outputs:
1 2 4 6 11 12