This is a code I wrote for bubble sort. I gave a comment //this line due to which I'm unable to run this program. Every time the first element of the array needs to be stored in 'temp'.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[7]={7,8,5,2,4,6};
int temp;
for(int i=0;i<7;i++)
{
temp=arr[0]; //this line.
for(int j=0;j<7-i;j++)
{
if(temp<arr[j])
temp=arr[j];
else
swap(arr[j],arr[j-i]);
}
}
for(int k=0;k<7;k++)
{
cout<<arr[k]<<endl;
}
return 0;
}
There were some issue with your program:
Array size should be 6 instead of 7
The for loop condition was incorrect
swap(arr[j],arr[j-i]) will break when j-i is less than 0(for instance i=1, j=0).
Program
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[6]={7,8,5,2,4,6};
for(int i=0;i<5;i++)
{
for(int j=0;j<5-i;j++)
{
if(arr[j]>arr[j+1])
swap(arr[j],arr[j+1]);
}
}
for(int k=0;k<6;k++)
cout<<arr[k]<<endl;
return 0;
}
Ideone
You seem flipped for() loops over... what I got - not the most elegant solution, but I stick to the same tools you're using. Mostly. I could make it as template and it would work with any appropriate container. std::sort sometimes implemented like that.
#include <iostream>
#include <algorithm>
void bubbleSort(int arr[], int n)
{
bool swapped;
for (int i = 0; i < n-1; i++)
{
swapped = false;
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
std::swap(arr[j], arr[j+1]);
swapped = true;
}
}
// no elements were swapped, array already sorted.
if (!swapped) break;
}
}
int main()
{
int arr[] = {7,8,5,2,4,6};
bubbleSort(arr, std::size(arr));
for( auto v : arr )
std::cout << v << " ";
std::cout << std::endl;
}
In C++11 and later <algorithm> can be replaced by <utility>, it's just for swap/size.
Related
I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElements(numbers, 5);
cout << sumOfElements(numbers, 5);
return 0;
}
void getElements(int numbers[], int size) {
for (int i = 0; i < size; i++) {
cin >> numbers[i];
}
}
int sumOfElements(int numbers[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
Here is a modified and simpler version of your program:
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main(){
const int num_elements_to_sum = 5;
array<int, num_elements_to_sum> elements;
for(int i=0; i<num_elements_to_sum; ++i){
cin>>elements[i];
}
int sum = accumulate(elements.begin(), elements.end(), 0);
cout<<"Sum: "<<sum<<endl;
return 0;
}
C++ has a dedicated fixed size array container, use this instead of C-style arrays. This then allows to use standard library algorithms instead of your own implementation (e.g. accumulate).
I created a function create() that generate 10 random numbers in a vector. And I am trying to create a function that removes duplicates. When I print the vector within the function remove_dup(), it works. But when I print it in the main function, it doesn't work. Please help. The other examples on here are not in a function.
#include <ctime>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <bits/stdc++.h>
using namespace std;
vector <int> listt;
vector <int> list2;
int number=0;
int create() {
srand((unsigned) time(0));
for (int i = 0; i < 10; i++) {
number = (rand() % 20) + 1;
listt.push_back(number);
}
return 0;
}
void print(vector <int> a) {
cout << "The vector elements are : ";
for(int i=0; i < a.size(); i++)
cout << a[i] << ' ';
}
vector <int> remove_dup(vector <int> listt) {
sort(listt.begin(), listt.end());
for(int i=0; i < listt.size(); i++){
if (listt[i-1]==listt[i]){
listt.erase(listt.begin()+i);
i=0;
}
}
return listt;
}
using namespace std;
int main() {
create();
print(listt);
cout<<endl;
remove_dup(listt);
print(listt);
}
Given an integer A which denotes the number of people standing in the queue.
A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected.
This continues until we are left with one person. Find and return the position of that person in the original queue.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A=10,p=0,i;
vector<bool> mark(A+1,true);
mark[0]=false;
for(i=0;i<=A;i=i+2)
{
p++;
if(p==2)
{
mark[i]=false;
p=0;
}
}
for(int j=0;j<A;j++)
{
cout<<mark[j];
}
for(i=0;i<A;i++)
{
if(mark[i]==true)
{
cout<<i<<endl;
}
}
}
i tried this but it only works for the first set of even numbers
ps:i am new here so please forgive me if i asked in a wrong way
If you are interested in a simple algorithm similar to yours, then please see this example:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int A = 10, currentSize = A;
vector<bool> mark(A, true);
while (currentSize > 1) {
for (int i = 0, j = 1; i < A; i++) {
if (mark[i]) {
if (j % 2 != 0) {
mark[i] = false;
currentSize--;
}
j++;
}
}
}
for (int i = 0; i < A; i++) {
if (mark[i]) {
cout << i + 1 << endl;
break;
}
}
return 0;
}
If you only need an answer to a problem with a faster algorithm, then I think that this will be correct:
#include <iostream>
using namespace std;
int main()
{
int A = 10, p = 0;
while (A / 2 != 0) {
A /= 2;
p++;
}
cout << pow(2, p);
return 0;
}
I used VS2017 to compile this code.
I saw some algorithm for a problem and rewrote it but I changed the fast_count_segment function's inner loop exit condition j=n1 to the break statement,the code timed out. Why does this happen?
The code runs fine otherwise but when I submit to the online grader, it shows code timeout, but as soon as I replace break with j=n1, it passes.
Shouldn't both be doing the same thing?
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> fast_count_segments(vector<pair<int,int>> &v, vector<int> points) {
vector<int> cnt(points.size());
int n1=v.size(),n2=points.size(),i,j,count;
for(i=0;i<n2;i++){
count=0;
for(j=0;j<n1;j++){
if(points[i]>=v[j].first && points[i]<=v[j].second)
count++;
else if(points[i]<v[j].first)
break; //j=n1; Changed this statement to break
}
cnt[i]=count;
}
return cnt;
}
int main() {
int n, m,a,b;
cin >> n >> m;
vector<pair<int,int>> v;
for (size_t i = 0; i < n; i++) {
cin >>a>>b;
v.push_back(make_pair(a,b));
}
vector<int> points(m);
for (size_t i = 0; i < points.size(); i++) {
cin >> points[i];
}
sort(v.begin(),v.end());
vector<int> cnt = fast_count_segments(v, points);
for (size_t i = 0; i < cnt.size(); i++) {
cout << cnt[i] << ' ';
}
cout<<endl;
return 0;
}
I am filling up an adjacency list of vector with pairs given by :
vector<pair<int, int>> adj[1000];
I am doing a depth first search on the list but experiencing some weird behaviour. The first print statement prints some value which means I have some items in adj[s][0], adj[s][1], adj[s][2] and so on. However when I calculate the size of adj[s] in the next line it prints out to be zero. Am I missing something here?. Is my definition for vector of pairs correct?. The adjacency list is correctly filled because when I ran cout << adj[s][0].first << endl; in dfs, it was correctly showing me the neighbors of each and every node.
Complete code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <climits>
#include <algorithm>
using namespace std;
vector<pair<int, int>> adj[1000];
bool visited[1000];
int nodeweight[1000];
void initialize()
{
for(int i = 0; i < 1000; i++)
visited[i] = false;
for(int i=0; i < 1000; i++)
adj[i].clear();
for(int i = 0; i <1000; i++)
nodeweight[i] = INT_MAX;
}
void dfs(int s)
{
visited[s] = true;
cout << adj[s][1].first << endl;
int minimum = INT_MAX, tovisit = 0;
for(int i = 0; i < adj[s].size(); i++)
{
cout << adj[s][i].second;
if(!visited[adj[s][i].first] && adj[s][i].second < minimum)
{
minimum = adj[s][i].second;
tovisit = adj[s][i].first;
}
}
nodeweight[tovisit] = minimum;
//dfs(tovisit);
}
int main() {
int N, E;
cin >> N >> E;
while(E--)
{
int i, j, w;
cin >> i >> j >> w;
adj[i].push_back(make_pair(j,w));
adj[j].push_back(make_pair(i,w));
}
initialize();
for(int i = 1; i <= N; i++)
{
dfs(i);
}
return 0;
}
You are clearing adj again after filling in initialize().
First you fill adj in the while loop in main. Then you call initialize() which includes this loop clearing all vectors in it:
for(int i=0; i < 1000; i++)
adj[i].clear();
Then you have cout << adj[s][1].first << endl; in dfs which is undefined behavior because there are no elements in adj[s]. The fact that you seem to get the correct results is just coincidental undefined behavior (although practical it is because the memory holding the vector data was not cleared.)
adj[s].size() is correctly reported as 0.