Bubblesort Driving me nuts - c++

This is pretty straightforward question. I checked online with the bubble sort code, and it looks like i am doing the same. Here's my complete C++ code with templates. But the output is kinda weird!
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
for(int j=0; j<i-1; j++){
if(a[j+1]>a[j]){
cout<<"Yes at j="<<j<<endl;
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main(){
int a[] = {1,2,6,3,4,9,8,10};
sort<int>(a,8);
for(int i = 0; i<8; i++){
cout<<a[i]<<endl;
}
return 0;
}
Output:
But when i slightly change the logic to try to sort it on ascending order. i.e., changing to : if(a[j+1]<a[j]) , The output is fine!
Where am i doing this wrong?
Thanks in advance!

The problem with your code is that you try to bubble stuff down, but loop upward. If you want to bubble stuff down, you need to loop downward so an element that needs to go down goes down as far as it needs to. Otherwise, with every iteration of i you only know that an element may be bubbled down one space.
Similarly, if you bubble things upwards, you also need to loop upwards.
If you want to see what happens, here's your code with some output statements so you can follow what's going on:
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=0; j<i-1; j++){
if(a[j+1]>a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
for(int k = 0; k < size; k++) {
cout << "\t a[" << k << "]: " << a[k] << endl;
}
cout << endl;
}
}
cout << "\n" << endl;
}
}
int main(){
int a[] = {1,2,6,3,4,9,8,10};
cout << "initially:" << endl;
for(int k = 0; k < 8; k++) {
cout << "a[" << k << "]: " << a[k] << endl;
}
cout << "\n" << endl;
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}
If you run this, you can see that for entries with higher index, there aren't enough iterations left to bubble them down all the way to where they need to go.
Also, here's code with your bubbling-down fixed (i.e. sorting in reverse order):
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=size - 1; j>i; j--){
if(a[j-1]<a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}
int main(){
int a[] = {1,2,3,4,5,6,8,10};
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}

When using bubble sort, you need to keep in mind in which directions your "bubbles" move. You first have to pick the biggest/smallest element from all the array and move it to the end at position n-1. Then pick the next one and move it to to position n.
for (int i=size; i>1; i=i-1) { // << this is different
for (int j=0; j<i-1; j=j+1) {
if (a[j] < a[j+1]) {
std::swap(a[j], a[j+1]);
}
}
}
See here for an even better implementation.

It is a logic problem:
for(int i = 0; i < size; i++){
for(int j = 0; j < (i); j++){
if(a[i] > a[j]){
cout<<"Yes at j="<<j<<endl;
T temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
You should change the a[j+1] for a[i]

You are comparing and swapping wrong numbers, look for differences here:
template <class T>
void sort(T a[], int size){
for(int i = 0; i < size; i++){
for(int j = i+1; j < size; j++){
if(a[i] < a[j]){
cout << "Yes at j=" << j << endl;
//swap(a[j], a[j+1]);
T temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}

Related

Display first even and then odd elements in a C++array

I'm a C++ newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C++ knowledge, so no advanced functions. Here's my code:
#include <iostream>
using namespace std;
int main()
{
int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++) {
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++) {
if (vector[i] % 2 == 0) {
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0) {
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++) {
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++) {
cout << " " << odd[i] << " ";
cout << endl;
}
return 0;
}
If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:
#include <sstream>
#include <stddef.h>
#include <iostream>
int main () {
std::stringstream oddStr;
std::stringstream evenStr;
static constexpr size_t vecSize{100};
int vec[vecSize] = {10, 5, 7, /*other elements...*/ };
for(size_t vecIndex = 0; vecIndex < vecSize; ++vecIndex) {
if(vec[vecIndex] % 2 == 0) {
evenStr << vec[vecIndex] << " ";
} else {
oddStr << vec[vecIndex] << " ";
}
}
std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}
Storing and sorting the elements are always expensive.
Basically, it would be better to sort them first.
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
int mergedArrays[5];
int evenNumbers[5];
int oddNumbers[5];
for(int i=0;i<5;i++){
cin>>numbers[i];
}
int temp=numbers[0];
//bubble sort
for(int i = 0; i<5; i++)
{
for(int j = i+1; j<5; j++)
{
if(numbers[j] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
int nEvens=0;
int nOdds=0;
for(int i = 0; i<5; i++)
{
if(numbers[i]%2==0)
{
evenNumbers[nEvens]=numbers[i];
nEvens++;
}
else if(numbers[i]%2!=0)
{
oddNumbers[nOdds]=numbers[i];
nOdds++;
}
}
int lastIndex=0;
//copy evens
for(int i = 0; i<nEvens; i++)
{
mergedArrays[i]=evenNumbers[i];
lastIndex=i;
}
//copy odds
for(int i =lastIndex; i<nOdds; i++)
{
mergedArrays[i]=oddNumbers[i];
}
return 0;
}
If you have to just output the numbers in any order, or the order given in the input then just loop over the array twice and output first the even and then the odd numbers.
If you have to output the numbers in order than there is no way around sorting them. And then you can include the even/odd test in the comparison:
std::ranges::sort(vector, [](const int &lhs, const int &rhs) {
return ((lhs % 2) < (rhs % 2)) || (lhs < rhs); });
or using a projection:
std::ranges::sort(vector, {}, [](const int &x) {
return std::pair<bool, int>{x % 2 == 0, x}; });
If you can't use std::ranges::sort then implementing your own sort is left to the reader.
I managed to find the following solution. Thanks you all for your help.
#include <iostream>
using namespace std;
int main()
{
int N{0}, vector[100], even[100], odd[100], merge[100], i{0}, j{0}, k{0}, l{0};
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++)
{
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++)
{
if (vector[i] % 2 == 0)
{
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0)
{
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++)
{
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++)
{
cout << " " << odd[i] << " ";
cout << endl;
}
for (i = 0; i < k; i++)
{
merge[i] = odd[i];
}
for (int; i < j + k; i++)
{
merge[i] = even[i - k];
}
for (int i = 0; i < N; i++)
{
cout << merge[i] << endl;
}
return 0;
}
You can use Bubble Sort Algorithm to sort whole input. After sorting them using if and put odd or even numbers in start of result array and and others after them. like below:
//Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Insert In array
int result[100];
if(odd[0]<even[0])
{
for (int i = 0; i < k; i++)
{result[i] = odd[i];}
for (int i = 0; i < j; i++)
{result[i+k] = even[i];}
}else
{
for (int i = 0; i < j; i++)
{result[i] = even[i];}
for (int i = 0; i < k; i++)
{result[i+k] = odd[i];}
}

Implementing Gauss Seidel iterative method on C++

I am trying to implement the Gauss seidel Iterative method in C++. i have a very messy code because i am still learning. for some reason my while loop seems to run without implementing the loop at all. I cannot get do while to work either.
The test matrix im using is
number of equations=2
x[0][0]=4
x[0][1]=2
x[1][0]=1
x[1][1]=3
b[0][0]=1
b[1][0]=-1
accuracy=0.2
the loop should continue until K has become less than accuracy.
The results should be;
x1=0.4583
x2= 0.4681
(i printed the F matrix just to make sure that part was working correct)
k=0.136
iterations performed=2
Again sorry for the messy code, like i said i am still learning.
Also i've tested the maths on separate codes and it works perfectly.
int main()
{
int n,i,j,p=0,l=0;
cout<<"Enter number of Equations = ";
cin>>n;
double a[n][n],b[n-1][1],F[n-1][1],x[n-1][1],T[n-1][1],e,k,B,C;
cout<<"[a].[x]=[b]"<<endl;
cout<<"Enter Matrix a:"<<endl;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
cout<<"a["<<i<<","<<j<<"] = ";
cin>>a[i][j];
}
cout<<"Enter Matrix b:"<<endl;
for(j=0;j<n;j++)
{
cout<<"b[0,"<<j<<"] = ";
cin>>b[0][j];
}
cout<<"Enter the Accuracy = ";
cin>>e;
for (i=0;i<n;i++){
T[i][0]=0;
}
for(i=0;i<n;i++){
x[i][0]=0;
}
for(i=0;i<n;i++){
F[i][0]=0;
}
while (k>=e){
C=0;
p=p+1;
k=0;
for(i=0;i<n;i++){
B=0;
T[i][0]=(b[i][0]/a[i][i]);
C=a[i][i];
for (j = 0; j < n; j++) {
if (j!=i)
B=B+(a[i][j])*(x[j][0]);
}
x[i][0]=T[i][0]-(B/C);
}
cout<<x[0][0]<<endl;
cout<<x[1][0]<<endl;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++){
F[i][0]=F[i][0]+(a[i][j]*x[j][0]);
}
}
for(i=0;i<n;i++){
F[i][0]=(F[i][0]-b[i][0]);
}
for(i=0;i<n;i++){
k=k+((F[i][0])*F[i][0]);
}
k=sqrt(k);
}
for (i=0;i<n;i++){
cout<<"x"<<i+1<<"="<<x[i][0]<<endl;}
cout<<"number of iterations used: "<<p<<endl;
for (i=0;i<n;i++){
cout<<"F"<<i+1<<"="<<F[i][0]<<endl;}
cout<<"k="<<k<<endl;
return 0;
}
Edit: i tried giving k an initial value and that goes infinitely and the pro gram crashes.
Heres are a run down.
The 3 important Matrixes are a,x and b.
ax=b
each row is changed into an equation and solved for x(i) with initial value for all the position in matrix x to be 0.
after completing this for all values in matrix x the accuracy "k" is checked by function: ax-b=matrix F, All values of F are then squared, added and under root to get k which is checked against e.
the results are:
x1=0
x2=0
number of iterations used: 0
F1=0
F2=0
k=2.96439e-323
First please note that the method you implement is the Jacobi iterative method, not Gauss-Seidel method.
There were several issues in your code:
k was not initialized: it must me set to a large value before the while loop, and set to 0 prior the calculation inside this loop
Some vectors were not initialized at the good size: n-1 instead of n
The F[.] vector should be reset to 0 at each iteration, not only at the start of the program
Moreover, I made some other modifications
I replaced variable length arrays (not C++) by std::vector
I replace [n][1] arrays by [n] vectors
I tried to avoid some i, j global variables
Here is a working code:
#include <iostream>
#include <cmath>
#include <vector>
using std::cin, std::cout;
int main() {
int n, p = 0;
cout << "Enter number of equations = ";
cin >> n;
double e , k, C;
std::vector<double> b(n), F(n, 0), x(n, 0), T(n, 0);
std::vector<std::vector<double>> a(n, std::vector<double> (n));
cout << "[a].[x]=[b]" << "\n";
cout << "Enter Matrix a:" << "\n";
for (int i = 0;i < n; i++) {
for(int j = 0; j < n; j++) {
cout << "a[" << i << ","<< j << "] = ";
cin >> a[i][j];
}
}
cout << "Enter Vector b:" << "\n";
for(int j = 0; j < n; j++)
{
cout << "b[" << j << "] = ";
cin >> b[j];
}
cout << "Enter the Accuracy = ";
cin >> e;
k = 1e10;
while (k >= e){
p = p + 1;
for (int i = 0; i < n; i++) {
double B = 0;
T[i] = b[i]/a[i][i];
C = a[i][i];
for (int j = 0; j < n; j++) {
if (j!=i)
B += a[i][j] * x[j];
}
x[i] = T[i]-B/C;
}
cout << x[0] << "\n";
cout << x[1] << "\n";
for (int i = 0; i < n; i++)
{
F[i] = 0.0;
for (int j = 0; j < n; j++){
F[i] = F[i] + a[i][j]*x[j];
}
}
for (int i = 0; i < n; i++){
F[i] = F[i]-b[i];
}
k = 0.0;
for (int i = 0;i < n;i++) {
k += F[i] * F[i];
}
k = std::sqrt(k);
}
cout << "Solution :\n";
for (int i = 0; i < n; i++){
cout << "x" << i << "=" << x[i] << "\n";
}
cout << "number of iterations used: " << p <<"\n";
for (int i = 0; i< n; i++){
cout <<"F" << i << "=" << F[i] << "\n";
}
cout << "Final error = " << k << "\n";
return 0;
}

How to find factors of each number in an array

I have an array of numbers input by the user, the program then sorts it in ascending order. I just need to find a way to get the factors of each number in the array and have it be printed out
#include "stdafx.h"
#include <iostream>
#include <limits>
#define MAX 200
using namespace std;
int arr[MAX];
int n, i, j, k;
int temp;
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of numbers to read: ";
cin >> n;
//check bound
if (n<0 || n>MAX)
{
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++)
{
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
cout << endl;
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
for (i = 0; i<n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << endl;
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl <<endl;
//trying to find factors
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++i)
{
if (arr[i] % k == 0)
cout << k << endl;
}
system ("pause")
return 0;
}
I want it to print each number from the array with
"The factors of (number) are ...'
"The factors of (next number) are ..."
and so on
The final for-loop should be loop with k and you forgot to increment k.
You should also write i-loop:
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
In addition, as pointed out by #LocTran, the upper bound of outer loop should be n-1.
Alternatively, you can easily sort arr using std::sort as follows:
std::sort(arr, arr+n);
Then your code would well work for you:
Live Demo
There are some issues with your source code.
1> Sorting problem with for outer loop
//sorting - ASCENDING ORDER
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
The upper bound of outer loop should be (n-1), not n as following but maybe you're lucky you won't see the problem when n < MAX. In case of n == MAX you will see the problem
//sorting - ASCENDING ORDER
//for (i = 0; i < n; i++)
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
2> The print functionality for entire array, you should add the outer loop for index of your array, and change the i++ by k++ in your loop as well
//trying to find factors
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++i)
{
if (arr[i] % k == 0)
cout << k << endl;
}
should be replaced by
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
//for (k = 1; k <= arr[i]; ++i)
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
Here is my solution based on modified source code
#include <iostream>
#include <limits>
#define MAX 200
using namespace std;
int arr[MAX];
int n, i, j, k;
int temp;
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of numbers to read: ";
cin >> n;
//check bound
//if (n<0 || n>MAX)
if (n<0 || n>MAX)
{
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++)
{
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
cout << endl;
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
//for (i = 0; i < n; i++)
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << endl;
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl << endl;
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
//for (k = 1; k <= arr[i]; ++i)
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
return 0;
}

cpp pass by reference

i wrote a simple sorting code on pass by reference. here i am passing an array to function and then performing the sorting operation. after passing the array i am printing the entire array as entered by user then performing the sorting operation(in descending order) but after sorting when i print the sorted array i get an output that the array index '0' contains the value '41'. if i enter the numbers less than '41' then the sorted array is displayed as '41',and then the other numbers in sorted manner. Please explain why i am getting such an output.
#include<iostream>
using namespace std;
int sort_array(int *p);
int main() {
int arr[10];
for (int i=0; i<10; i++) {
cout << "enter " << (i+1) << " value:";
cin >> arr[i];
cout << "\n";
}
sort_array(arr);
return 0;
}
int sort_array(int *p) {
int c=0;
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << "arr:"<<p[0];
cout<<"\n";
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (p[j] < p[j+1]) {
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
cout << "\n";
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << p[0];
}
It appears that you are trying to do a bubble sort on your array in sort_array(), but the logic is wrong. Try using this code instead:
int sort_array(int *p) {
int c=0;
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << "arr:" << p[0];
cout << "\n";
for (int i=0; i < 10; i++) {
for (int j=1; j < (10-i); j++) {
if (p[j-1] > p[j]) {
c = p[j-1];
p[j-1] = p[j];
p[j] = c;
}
}
}
cout << "\n";
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout<<p[0];
}
The problem is in your sorting. j is from 0 to 9, and than you access p[j+1] when j = 9, p[10] is outside your array boundaries.
So fix your following part to proper sorting.
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(p[j]<p[j+1])
{
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
}
Clarification: the code above is the problematic part of the original code posted. This is NOT the fixed sorting. That is the part to be fixed.
for(int i=0;i<10;i++)
{
for(int j=0;j<9;j++)
{
if(p[j]<p[j+1])
{
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
}
the sorting works fine once i changed the limit of inner loop. the problem was accessing the array index [10] but i had it declared till index [9].

Bubble Sort Display

#include <iostream>
#include <string>
using namespace std;
void bubbleSort(int data[], int n);
int main()
{
cout << "Enter ten unsorted integers..." << endl;
int a[10];
for (int i = 0; i < 10; ++ i)
{
cout << "[" << i << "] = ";
cin >> a[i];
}
cout << endl << "Unsorted List = ";
for (int i = 0; i < 10; ++i)
cout << a[i] << ", ";
cout << endl;
cout << "Sorting..." << endl;
cout << "Sorted List = ";
bubbleSort(a, 10);
}
void bubbleSort(int data[], int n)
{
int j = 0;
bool nextEnd = true;
while (nextEnd)
{
nextEnd = false;
++j;
for (int i = 0; i < n - j; ++i)
{
if (data[i] > data[i+1])
{
int temp = data[i];
data[i] = data[i+1];
data[i+1] = data[i];
nextEnd = true;
}
}
}
for (int i = 0; i < 10; ++i)
cout << data[i] << ", ";
}
The program is really simple. Input ten values to an array. Display them unsorted. Send them into the bubbleSort function, sort them and finally display the sorted list. The problem I'm having is I don't get the outputting back to work. I tested with the last line of code but that doesn't work. I don't think my sorting is messed up either. How can I display this sorted list properly?
There is at least one error in the bubble sort. The assignment to data[i+1] is not correct. It should be:
data[i+1] = temp;
The problem is your 'swap'. It should be:
int temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
Edit-Tested and works fine with the correction.