Bubble Sorting Algorithm in C++ - c++

I'm trying to implement the bubble sorting algorithm to an array of integers, the function which sorts the array takes an array as a parameter and suppose to return the sorted array.
Here is the code:
#include <iostream>
using namespace std;
int* BubbleSort(int data[]){
for(int i=0; i<sizeof(data)/sizeof(data[0])-1; i++){
for(int j=0; j<sizeof(data)/sizeof(data[0])-1-i; j++){
if(data[j+1]>data[j]){
int temp = data[j+1];
data[j+1]=data[j];
data[j]=temp;
}
}
}
return data;
}
int main()
{
int data[]={8,4,9,7,6,5,13,11,10};
int *a=BubbleSort(data);
cout<<"{";
for(int i=0; i<sizeof(data)/sizeof(data[0]); i++){
cout<<a[i];
if(i==sizeof(data)/sizeof(data[0])-1){
cout<<"}"<<endl;
}else{
cout<<",";
}
}
return 0;
}
The output I'm getting:
{8,4,9,7,6,5,13,11,10}

You must pass in the size of the array because an array it decays to the pointer to its first element (element 0).
void BubbleSort(int data[], int size){
for(int i(0); i != size; ++i){
for(int j(i + 1); j != size; ++j){
if(data[i] > data[j]){
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}

Maybe too late, but maybe in the future it will be useful,
Try to use this code
...
/**
* Sort array of integers with Bubble Sort Algorithm
*
* #param arr Array, which we should sort using this function
* #param arrSZ The size of the array
* #param order In which order array should be sort
*
* #return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
for (int i = 0; i < arrSz; ++i)
{
for (int j = 0; j < (arrSz - i - 1); ++j)
{
// Swapping process
if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
return; // Optional because it's a void function
}// end bubbleSortInt
...
Then use it in your main function like below,
...
double integers[array_size];
const int array_size = 10;
string order = "ascending";
bubbleSortInt(integers, array_size, order)
for (int i = 0; i < array_size; ++i)
{
cout << integers[i] << "\t";
}
...
Have a detailed look at the bubble sort algorithm -> https://github.com/teamroyalcoder/algorithms#bubble-sort-algorithm
This is a GitHub repo where you will find a bunch of algorithms with full details and source code written in c++ https://github.com/teamroyalcoder/algorithms

Related

Applying selection sort on an array of integers

int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i<size-1; i++){
int temp = arr[i];
for(int j = i+1; j < size; j++){
if(arr[j] < temp){
temp = arr[j];
}
}
swap(temp, arr[i]);
}
I am trying to apply the selection sort algorithm on the given array, but the output I am getting is only [1,1,1,1,1,1], I am finding the minimum element through the inner loop, Ican't figure out what is going wrong?
Slightly modified your code;
You need to pass reference(address) to both elements to take place of swapping contents
int arr[] = { 7, 1, 10, 8, 3, 11, 0, 12, 5, 8 };
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i < size; i++)
{
auto temp = std::min_element( arr + i, arr + size );
std::swap( arr[i], *temp );
}
You have to add algorithm header to use std::min_element
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i<size-1; i++){
int temp = arr[i];
int pos = i;
for(int j = i+1; j < size; j++){
if(arr[j] < temp){
temp = arr[j];
pos = j;
}
}
if(pos != i)
std::swap(arr[pos], arr[i]);
}
This should work.
It is suggested not to use using namespace std;. There is a plethora of reasons why you should not; that I will not mention.
By the way I tried to keep some of your variables the same but to be honest, I didn't. It is better to create variable names that explain what the code is doing. It makes your code a lot more legible and readable.
So opt out of one letter variables. It is fine in for loops, however this is a special case.
Now, here is another alternative suggested by #user4581301 & #Swift -Friday Pie. This method is using std::size using c++17.
For example:
#include <iostream>
#include <utility> // to use the swap() function.
#include <iterator> // to use std::size() function.
int main()
{
int arr[] = { 7,4,10,8,3,1 };
// This --> int size = sizeof(arr) / sizeof(arr[0]); is archaic.
const int length = static_cast<int>(std::size(arr)); // Call this something other than "size"; you can run into issues.
// We use static_cast<int> as a implicit conversion, and the obvious std::size(arr)).
// Going through the elements
for (int StartOfIndex = 0; StartOfIndex < length - 1; ++StartOfIndex)
{
// smallest is the index of the smallest element we’ve encountered this iteration
int smallest = StartOfIndex;
// Looking for a smaller element..
for (int current = StartOfIndex + 1; current < length; ++current)
{
// if we found an element smaller than our last; take note.
if (arr[current] < arr[smallest])
smallest = current;
}
// swap StartOfIndex with smallest.
std::swap(arr[StartOfIndex], arr[smallest]);
}
//Prints array.
for (int index = 0; index < length; ++index)
std::cout << arr[index] << " ";
std::cout << "\n";
return 0;
}
Output: 1 3 4 7 8 10
The first mistake you made in writing for loop's condition, don't use swap(temp, array[i]); yet try to get the basics first.
#include <iostream>
using namespace std;
int findsmall(int arr[], int i, int size){
int s, pos, j;
s = arr[i];
pos = i;
for(j = i+1; j < size; j++){
if(arr[j] < s){
s = arr[j];
pos = j;
}
}
return pos;
}
int main() {
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
int smallnum;
int temp;
int count = 0;
cout << "Original array: ";
for(int i = 0; i < size; i++){
if(i < size - 1){
cout << arr[i] << ", ";}
else{
cout << arr[i];
}
}
cout << endl;
for(int i = 0; i < size; i++){
smallnum = findsmall(arr,i, size);
temp = arr[i];
arr[i] = arr[smallnum];
arr[smallnum] = temp;
count++;
}
cout << "Sorted array: ";
for(int i = 0; i < size; i++){
if(i < size - 1){
cout << arr[i] << ", ";}
else{
cout << arr[i];
}
}
cout << endl;
return 0;
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
selectionSort(arr,size);
This should work.

C++ why is there a segmentation fault in my pointer selection sort?

Below is my c++ code. I am trying to implement a selection sort using pointers (start and end). The code compiles, but I am getting a segmentation fault before it will sort the random generated list (currently only prints the random numbers).
Any help as to why this is and how to fix it would be greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
void selectionSort(int *start, int *stop) {
for (int i = *start; i < *stop - 1; ++i) {
int min = i;
for (int j = i + 1; j < *stop; ++j) {
if ((&start[0])[j] < (&start[0])[min])
min = j;
}
swap((&start[0])[i], (&start[0])[min]);
}
}
int main()
{
int size = 10;
int* data = new int[size];
for (int i = 0; i < size; ++i)
{
data[i] = rand() % size;
}
for (int k = 0; k < size; k++)
{
cout << data[k] << " ";
}
cout << endl;
selectionSort(data, data+size);
for (int j = 0; j < size; j++)
{
cout << data[j+1] << " ";
}
return 0;
}
The general logic in your function is in the right direction. However, you seem to be confused between values of the elements of the array and the indexing used to access the elements of the array.
The line
for (int i = *start; i < *stop - 1; ++i)
shows the first signs of the confusion.
You are initializing i with the value of the first element of the array and incrementing the value in the subsequent iterations of the loop. That is not correct. Incrementing the value of the first element of the array does not make logical sense.
*stop causes undefined behavior since stop points to a place one past the last valid element.
You need to use int* i, int* j, and int* min to properly sort the elements. That also means updating almost the entire function accordingly. Here's an updated function that works for me.
void selectionSort(int *start, int *stop) {
for (int* i = start; i < (stop - 1); ++i) {
int* min = i;
for (int* j = i + 1; j < stop; ++j) {
if (*j < *min)
{
min = j;
}
}
swap(*i, *min);
}
}
Also, the following lines in main are not correct. You end up accessing the array using an out of bounds index.
for (int j = 0; j < size; j++)
{
cout << data[j+1] << " ";
}
Replace them by
for (int k = 0; k < size; k++)
{
cout << data[k] << " ";
}

Dynamic Arrays and user input c++

I'm writing a program for my C++ class that takes the user input for the size of a int and char array, fills the arrays with random values (numbers 0-100, letters A-Z) then sorts, reverses, and displays both arrays.
For the most part the program works and I understand the logic I used here, but...
After running and debugging the code multiple times. I noticed that when the arrays were being filled with values, the first element, even though it was actually being given a value, it would not print the assigned value it was given in ascending order, but would in a descending order? I don't understand this at all.
NOTE: I have to use template functions for the sorting, reversing and display of the arrays.
template <class T>
void sort(T *arr, int a) {
T temp;
for (int i = 0; i < a; i++) {
for (int j = a; j > 0; j--) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
template <class T>
void reverse(T *arr, int a) {
T temp;
for (int i = 0; i < a / 2; i++) {
temp = arr[i];
arr[i] = arr[a - i];
arr[a - i] = temp;
}
}
template <class T>
void display(T *arr, int a) {
for (int i = 0; i < a; i++) {
cout << arr[i] << ", ";
}
cout << endl;
}
template<class T>
void save(T *arr, int a) {
sort(arr, a);
display(arr, a);
reverse(arr, a);
display(arr, a);
}
int main() {
int x, y;
cout << "Please enter a number for an array of data type \"int\"" << endl;
cin >> x;
cout << "Please enter a number for an array of data type \"char\"" << endl;
cin >> y;
int *arr1 = new int[x];
char *arr2 = new char[y];
for (int i = 0; i < x; i++)
cout << (arr1[i] = rand() % 100 + 1);
srand(time(nullptr));
for (int i = 0; i < y; i++)
cout << (arr2[i] = rand() % 26 + 65);
system("cls");
save(arr1, x);
save(arr2, y);
delete[]arr1;
delete[]arr2;
system("pause");
return 0;
}
You are using the complete length here:
save(arr1, x);
save(arr2, y);
So in reverse
arr[i] = arr[a - i];
arr[a - i] = temp;
you need to -1 on the length or you'll get an invalid index when i == 0
arr[i] = arr[a - 1 - i];
arr[a - 1 - i] = temp;
Like R Sahu says, in sort
for (int j = a; j > 0; j--) {
you need to -1 because a is the length which will be an invalid index.
for (int j = a-1; j > 0; j--) {
As a side note, you can declare Temp t inside of the for loop in reverse and inside of the if in sort because it is only used in those scopes.
EDIT:
Also I overlooked, in sort you need to change
j>0
to
j >= 0
that way you access the first element of the array as well.
You have a off-be-one error in couple of places.
for (int j = a; j > 0; j--) {
is incorrect. a is an invalid index for the array. Change that line to use j = a-1:
for (int j = a-1; j > 0; j--) {
You have a similar, off-by-one, error in reverse. Instead of
arr[i] = arr[a - i];
arr[a - i] = temp;
you need to use:
arr[i] = arr[a - i - 1];
arr[a - i - 1] = temp;
Your implementation of sort is not correct. I don't want to get into the algorithmic details here but changing the order of the values used for j seems to fix the problem.
for (int i = 0; i < a; i++) {
for (int j = i+1 ; j < a ; j++) {
// The swapping code.
}
}
You are using bubble sort that is O(n^2) time complexity. Consider using faster algorithm. If you don't want to implement it on your own, use sort() function. It's complexity is about O(n log n), which is very good.
http://www.cplusplus.com/reference/algorithm/sort/
#include <iostream>
#include <algorithm>
using namespace std;
bool comp(int i1, int i2) { // comp function is to compare two integers
return i1 < i2;
}
int main() {
int x[30];
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x[i];
}
sort(x, x + n, comp); // if you don't provide comp function ( sort(x, x+n) ), sort() function will use '<' operator
for (int i = 0; i < n; i++) {
cout << x[i] << " ";
}
return 0;
}

Selection Sort in c++

i'm trying to understand selection sort from this video:
https://www.youtube.com/watch?v=79AB11J5BqU
this is my current code :
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
Am i doing the selection sort just like the video?
or am i instead doing buble sort ?
Thanks
In selection sort you find a minimal (or maximal) element and put it to top (bottom), then repeat it again for the rest of list.
It would be a selection sort, but you don't need to do swap every number you compare to find the smallest one. Store smallest number index in each internal loop and do one swap at the end of it.
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}

Calling a sort function on an array c++

I am using an insertion sort function to sort a 5000 int ascending array. when i pass the array's address to the function call, i get [Error] name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]. Maybe I should use a vector but I am unfamiliar with them. Maybe I coded something wrong?
#include <iostream>
#define SIZE 5000 //array size
using namespace std;
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
int main() {
int a[SIZE];
int count = 1;
for(int i=0; i<SIZE; i++) {
a[i] = count;
count++;
}
for(int i = 0; i < SIZE; i++) {
printf("%d\t", a[i]);
}
insertionSort(&a[i], SIZE);
}
You probably want to call
insertionSort(a, SIZE)
// insertionSort(&a[i], SIZE); Here you haven't declared i in funciton main(), only in your for loop. And the call to insertionSort is outside of your loop.
Passing (&a)[0] and a mean the same thing.