Bubble sort logical error? - c++

I am trying to do a bubble sort, but I don't know what's happening in my code. I am a noob so sorry if the code I wrote seems obvious ^.^
main() {
int a[5], i, j, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for ( i = 0; i <= 4; i++ ) {
cin >> a[i];
}
for ( i = 0; i <=4; i++ ) {
smallest = a[i];
for ( j = 1; j <= 4; j++ ) {
if ( smallest > a[j] ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << endl << endl;
for ( i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
system("pause");
}
Any answer will be highly appreciated. Thanks!

Your bubblesort almost appears to be a selection sort. Bubblesort looks at pairs of items and swaps them if necessary. Selection sort looks for the lowest item in the rest of the array, and then swaps.
#include <iostream>
#include <utility>
using std::cin;
using std::cout;
using std::endl;
using std::swap;
void bubblesort(int a[5])
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < 4; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
}
}
}
void selectionSort(int a[5])
{
for (int i = 0; i < 4; i++)
{
int smallest = i;
for (int j = smallest; j < 5; j++)
{
if (a[smallest] > a[j])
{
smallest = j;
}
}
if (smallest != i)
{
swap(a[i], a[smallest]);
}
}
}
int main(int argc, char* argv[])
{
int a[5];
cout << "Enter 5 numbers: " << endl;
for (int i = 0; i < 5; i++ )
{
cin >> a[i];
}
//selectionSort(a);
bubblesort(a);
cout << endl << endl;
for (int i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
}

Related

SelectionSort in c++ not sorting*

I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.

is there other way to fill in array in C++ without vector

So I have array A and B, two of them contain random numbers and I need to write in the C array initially even numbers of A and B and then odd. I have made this wtih vector but I wonder if there is other way to do it like in Javascript there are methods like .unshift(), .push() etc
#include<iostream>
#include<vector>
using namespace std;
int main() {
const int n = 4;
int A[n];
int B[n];
vector<int>C;
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
C.push_back(A[i]);
}
if (B[i] % 2 == 0)
{
C.push_back(B[i]);
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
C.push_back(A[i]);
}
if (B[i] % 2 != 0)
{
C.push_back(B[i]);
}
}
cout << endl;
for (int i = 0; i < C.size(); i++)
cout << C[i] << " ";
}
I would suggest interleaving A and B initially:
for (int i = 0; i < n; i += 1)
{
C.push_back(A[i]);
C.push_back(B[i]);
}
And then partitioning C into even and odd elements:
std::stable_partition(C.begin(), C.end(), [](int i) { return i % 2 == 0; });
vector::push_back is the simplest way to have a collection that grows as you add things to the end.
Since you have fixed size for A and B, you could make them primitive arrays instead, which is what you have done. But for C you don't know how long it will be, so a collection that has a changeable size is appropriate.
You can use std::array, if you know the size you need in compile time. You can then add using an iterator.
#include<vector>
using namespace std;
int main() {
const int n = 4;
int A[n];
int B[n];
std::array<int, n+n>C; // <-- here
auto C_it = C.begin(); // <-- here
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
*C_it++ = A[i]; // <-- here
}
if (B[i] % 2 == 0)
{
*C_it++ = B[i];
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
*C_it++ = A[i];
}
if (B[i] % 2 != 0)
{
*C_it++ = B[i];
}
}
cout << endl;
for (int i = 0; i < C.size(); i++)
cout << C[i] << " ";
}
Alternatively if you want to be more safe you can hold the next unwritten index and access elements with C.at(last++) = A[i], which checks for out-of-bounds and throws an exception instead of UB.
well you don't to change much.
first of declare C array as int C[n+n]; and declare a variable for incrementing through c array as int j=0;
and in if statements of loops do this C[j]=A[i]; j++; for first if and C[j]=B[i]; j++; for the second if statements
int main() {
const int n = 4;
int A[n];
int B[n];
int C[n+n];
int j=0;
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
C[j]=A[i];
j++;
}
if(B[i]%2==0){
C[j]=B[i];
j++;
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
C[j]=A[i];
j++;
}
if (B[i] % 2 != 0)
{
C[j]=B[i];
j++;
}
}
j=0;
cout << endl;
for (int i = 0; i < C[].lenght(); i++)
cout << C[i] << " ";
}

How do I put any value X after all the minimums in an array?

If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}

HackerRank says ~no response on stdout~. C++

I wrote this solution for the absolute permutation problem on HackerRank. It works fine on dev-C++ but doesn't work on Hackerrank. I've found that the code produces output when I remove the abs_perm(). What's the problem here?
#include <iostream>
using namespace std;
int arr[100000];
int check(int n, int k)
{
if ( (2*k == n) || (k == 0) || (n - 4*k == 0) )
return 1;
else if (k < n/2)
return check(n - 4*k, k);
else
return 0;
}
void swap(int &a, int &b)
{
int c = b;
b = a;
a = c;
}
void ini(int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = i+1;
}
}
void abs_perm(int n, int k)
{
for (int i = 0; i < k; i++)
{
swap(arr[i], arr[k+i]);
}
if (2*k == n)
return;
for (int i = n - 1; i > n - k - 1; i--)
{
swap(arr[i], arr[i-k]);
}
if (n - 4*k == 0)
return;
abs_perm(n - 4*k, k);
}
int main()
{
int T;
cin >> T;
int N[T], K[T];
for (int i = 0; i < T; i++)
{
cin >> N[i] >> K[i];
}
for (int i = 0; i < T; i++)
{
cout << N[i] << " " << K[i] << "\n";
}
for (int i = 0; i < T; i++)
{
if ( !check(N[i], K[i]) )
cout << "-1\n";
else
{
ini(N[i]);
abs_perm(N[i], K[i]);
for (int j = 0; j < N[i]; j++)
{
cout << arr[j] << " ";
}
cout << "\n";
}
}
return 0;
}
Array is a structure to use when you know at compile time the dimension of your structure. What you wrote at the begin in abs_perm() is not correct for standard compilers (in fact you don't know the dimension of your array). You can use a std::vector or a std::list which allocate memory dynamically or (bad solution) you can allocate an array with dimension that certainly contains all elements you will put inside.

How do i add all the values in my ascending array?

First i need to re-arrange all the values of my array into ascending order then add it afterwards. For example the user input 9 2 6, it will display in ascending order first ( 2 6 9 ) before it will add the sum 2 8 17.. The problem is my ascending order is not working, is there something wrong in my code?
#include <iostream>
#include<conio.h>
using namespace std;
int numberof_array, value[10], temp;
int i = 0, j;
void input()
{
cout << "Enter number of array:";
cin >> numberof_array;
for (i = 0; i < numberof_array; i++)
{
cout << "Enter value for array [" << i + 1 << "] - ";
cin >> value[i];
cout << endl;
}
}
void computation()
{
// this is where i'll put all the computation
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
for (i = 0; i <= numberof_array; i++)
{
for (j = 0; j <= numberof_array - i; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j];
value[j] = value[j + 1];
value[j + 1] = temp;
}
}
}
}
void display()
{
// display all the computation i've got
cout << "\nData after sorting: ";
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
getch();
}
int main()
{
input();
computation();
display();
}
void computation(){
for (int j = 0; j < numberof_array; j++) cout << value[j]<<"\t";
for (int i = 0; i <= numberof_array; i++) {
temp = value[i];
int temp_idx = i;
for (int j = i; j < numberof_array; j++) {
if (value[j] < temp) {
temp = value[j];
temp_idx = j;
}
}
int temp_swap = value[i];
value[i] = value[temp_idx];
value[temp_idx] = temp_swap;
}
}
How about changing your second function to something like above.
I have to agree with other commentators that your coding style is not preferred but there might be more to the story than meets the eye.