C++ Bubble Sorting and Selection Sorting - c++

Here's the problem.
Write a program that uses two identical arrays of at least 20 integers. It should call a function that uses the bubble sort algorithm to sort one of the arrays in ascending order. The function should keep a count of the number of exchanges it makes. The program then should call a function that uses the selection sort algorithm to sort the other array. It should also keep count of the number of exchanges it makes. Display these values on the screen.
Here's where my problem is. I can do void bubbleSort and void selectionSort and sort 20 random numbers that I input but I'm having a hard time trying to figure out how to add a counter for the number of exchanges in each of the sorting methods.
Also, the instruction says to use int bubbleSort(long [], int); and int selectionSort(long [], int);. I'm confused why I would be using int instead of void. Perhaps I use both?
Anyways, any help is greatly appreciated. Thank you.
edit: Here's what I have so far.
//Sorting Benchmarks
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Function Prototypes
void sortArray (int [], int);
void showArray (const int [], int);
int bubbleSort(long [], int);
int selectionSort(long [], int);
int main()
{
// Define an array with unsorted value
const int SIZE = 20;
int values[SIZE]{20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1);
// Display the values
cout << "The unsorted values are:\n";
showArray(values, SIZE);
//Sort the values.
sortArray(values, SIZE);
//Display them again.
cout << "The sorted values are:\n";
showArray(values, SIZE);
return 0;
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
count++
dispCount()
}
}
} while (swap);
}
void dispCount()
{
cout << "The current number of exchanges are " << count << endl;
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
system("PAUSE");
}
With this, I'm getting a million errors, the biggest one being in int main, where it says expected primary-expression before "int" and expected ';' before "int". I've checked and I feel all the ;'s are where they belong.

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void sortArray (int [ ], int ) ;
void showArray (int [ ], int ) ;
int count = 0;
int main ()
{
const int SIZE = 6;
int values[SIZE] = {7, 2, 3, 8, 9, 1} ;
cout << "The unsorted values are: \n";
showArray (values, SIZE) ;
sortArray (values, SIZE) ;
cout<< "The sorted values are: \n" ;
showArray (values, SIZE) ;
return 0;
}
void sortArray (int array [ ], int SIZE)
{
int temp;
bool swap;
do
{ swap = false;
for (int count = 0 ; count < (size - 1 ) ; count ++)
{
if (array [count] > array [count + 1] )
{
temp = array [count] ;
array [count] = array [count + 1] ;
array [count + 1] = temp ;
swap = true ;
count++;
dispCount();
}
}
} while (swap) ;
}
void dispCount(){
cout << "The current amount of swaps is " << count << endl;
}
void showArray (int array [ ], int size)
{
for (int count = 0 ; count < size ; count ++)
cout << array [count] << " " ;
cout << endl ;
}
Reference Links
Link 1
Link 2
Link 3

static int count = 0; in the head of function bubbleSort;
put the count++ after the code where you switch 2 numbers.
printf("%d", count); in the end.

The C Code I've written for you returns this output
You have provided this data
1 2 3 4 5 9 8 7 6
11 12
Selection sort on this array took 14 swap operation
Bubble sort on this array took 48 swap operation
You are asking for a counter variable that holds the number of swapping operations in bubble sort as well as in your selection sort program.
I've written a C code for your both problems.
Bubble sort
#include<stdio.h>
#define size 20
int Arr[size],i,j,counter=0;
void bubble();
int main()
{
printf("Enter your elements now\n");
for(i=0;i<size;i++)
scanf("%d",&Arr[i]);
printf("You have provided\n");
for(i=0;i<size;i++)
printf("\t%d",Arr[i]);
printf("\nPress any key to perform Bubble sort\n");
bubble();
printf("Result after Bubble sort\n");
for(i=0;i<size;i++)
printf("\t%d",Arr[i]);
printf("Bubble sort on this array took %d swap operation",counter);
return 0;
}
void bubble()
{
for(i=0;i<size;i++)
{
for(j=0;j<(size-1)-i;j++)
{
if(Arr[j]>Arr[j+1])
{
Arr[j] = Arr[j] + Arr[j+1];
Arr[j+1] = Arr[j] - Arr[j+1];
Arr[j] = Arr[j] - Arr[j+1];
counter++;
}
printf("\r");
}
}
}
Selection sort
#include<stdio.h>
#define size 20
void selection();
int findmin(int []);
int i,j,Arr[size],min,counter;
int main()
{
printf(" Enter your elements now \n");
for(i=0;i<size;i++)
scanf("%d",&Arr[i]);
printf("You have provided this data \n");
for(i=0;i<size;i++)
printf("\t%d",Arr[i]);
printf("\nPress any key to perform selection sort\n");
selection();
printf("Result after selection sort\n");
for(i=0;i<size;i++)
printf("\t%d",Arr[i]);
printf("Selection sort on this array took %d swap operation",counter);
}
void selection()
{
for(i=0;i<(size-1);i++)
{
j = findmin(Arr);
if(Arr[i]>Arr[j])
{
Arr[i] = Arr[i] + Arr[j];
Arr[j] = Arr[i] - Arr[j];
Arr[i] = Arr[i] - Arr[j];
counter++;
}
}
}
int findmin(int a[])
{
min = i;
for(j=i+1;j<size;j++)
{
if(a[j]<a[min])
min = j;
}
return(min);
}

Related

Getting a weird negative number in my output when using an array I modified in one function, in another function

I am writing a program that takes a user-inputted list of up to 25 integers, then prints the sorted list using bubble sorting, the sorted list in descending order, and some other info about the list like the median, minimum and maximum, and mode.
I have tested all of my functions within the program individually on an array I created using initializer lists (not from user input/cin) and they work fine, but when I run the program something is off. For example, when I input 1,2,3,4, the function that prints the sorted list in descending order prints 3,2,1, -858993460. It always leaves out the greatest integer and adds on -858993460 at the end no matter what values I put into the input array. Here's the relevant part of my code:
#include <iostream>
using namespace std;
void input(int ulist[26], int& n);
void Bubblesort(int ulist[26], int slist[26], int n);
void print(int list[26], int n);
int n;
void reversesort(int slist[26], int n);
void main()
{
int ulist[26], slist[26];
input(ulist, n);
cout << "Unsorted";
print(ulist, n);
cout << "Sorted";
Bubblesort(ulist, slist, n);
print(slist, n);
reversesort(slist, n);
cin >> n;
}
void input(int ulist[26], int& n)
{
int i(0), value;
cout << "enter value : \n";
cin >> value;
while (i < 25 && value != -999)
{
ulist[i] = value;
i++;
if (i < 25)
{
cin >> value;
}
}
n = i;
}
void Bubblesort(int ulist[26], int slist[26], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
slist[i] = ulist[i];
for (j = 25 - 1; j > 0; j--) //25 is Length of the array
for (i = 0; i < j; i++)
if (slist[i] > slist[i + 1])
{
temp = slist[i];
slist[i] = slist[i + 1];
slist[i + 1] = temp;
}
}
void print(int list[26], int n)
{
int i;
cout << " list of numbers are : \n";
for (i = 0; i < n; ++i)
{
cout << list[i] << '\n';
}
cout << "\n\n";
}
void reversesort(int slist[26], int n) //checked w online compiler, works
{
cout << "List of numbers in descending order is: \n";
for (int i = n - 1; i >= 0; --i)
cout << slist[i] << ", ";
cout << "\n";
}
I'm assuming this is some sort of memory problem and that the source of this has to do with passing slist, which was modified in the bubblesort function, through the functions I wrote. I'm pretty new to C++ (coming from python) so I'm assuming I'm missing something as far as passing arrays to functions is concerned.
EDIT: I guess to sum everything up - how can I take the data inputted in the input function and use that array in another function? And how can I take the array that has been sorted by the bubblesort function and use that array in another function?
The first instance of undefined behavior in your code is
if (slist[i] > slist[i + 1])
in Bubblesort.
Due to
for (j = 25 - 1; j > 0; j--)
for (i = 0; i < j; i++)
the maximum index accessed by this loop is slist[24] (24 from i + 1 where i < j and j = 25 - 1 = 24, so i = 23).
Your input is only 4 numbers, so only slist[0] through slist[3] are initialized. The remaining elements (slist[4] through slist[25]) are uninitialized. Reading from an uninitialized variable has undefined behavior.

Bubble sort the total number of comparisons and swaps

I have this code for bubble sort in c++. At first it generates random numbers and puts them inside an array. After that I call my bubbleSort function, which does the sorting. Everything works fine. However I was curious how can I find a number of total comparisons and number swapping that bubble sort makes?
I created a CountBubbleSort integer for comparisons. However I'm not sure in which part of my code should I increment it. I was thinking to add it after second for loop, inside first one. Hope you understand what I mean. Is it right or not? Number of comparisons defines this formula n*(n-1))/2. And with swaps it is 3*(n-1). But how can I implement it to my code? Thanks for the help guys.
void swap(double *xp, double *yp)
{
double temp = *xp;
*xp = *yp;
*yp = temp;
}
double *Data;
double* A;
double n, temp;
void generate(int _n, const char *_file);
void read(const char *_file);
void printArray(double arr[], int n);
void bubbleSort(double arr[], int n);
int main()
{
int m;
int CountBubbleSort = 0;
srand(time(NULL));
cout << "Amount of random numbers you want: ";
cin >> m;
cout << "Generating random data ..." << endl;
generate(m, "duom.txt");
cout << "Reading data" << endl;
read("duom.txt");
A = new double[n];
for (int i = 0; i < n; i++) {
A[i] = Data[i];
}
cout << "Randomly generated array" << endl;
printArray(A, n);
// Bubble Sort
bubbleSort(A, n);
cout << "Array after bubble sort" << endl;
printArray(A, n);
return 0;
}
void bubbleSort(double 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])
{
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
// Should I add CountBubbleSort += i here or not?
if (swapped == false)
break;
}
}
void printArray(double arr[], int n) {
for (int i = 0; i < n; i++) {
cout << A[i] << endl;
}
}
This is a relatively straightforward change:
Increment comparison count before the if statement
Increment the swap counter inside the if statement
Take two int& parameters for the count, like this:
void bubbleSortCounted(double arr[], int n, int& countComparisons, int& countSwaps);
The code incrementing the counters would look like this:
countComparisons++;
if (arr[j] > arr[j + 1])
{
countSwaps++;
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
The call from the main() would look like this:
int cmp = 0, swp = 0;
bubbleSort(A, n, cmp, swp);
std::cout << cmp << " comparisons, " << swp << " swaps" << std::endl;
However I was curious how can I find a number of total comparisons and number swapping that bubble sort makes? I created a CountBubbleSort integer for comparisons. However I'm not sure in which part of my code should I increment it.
There's exactly one line in your bubbleSort() function where you actually compare two elements in the array, so it stands to reason that if you want to count the number of times you compare elements, you should increment the counter either immediately before or immediately after the comparison happens.

Bubble sorting random numbers

I am trying to use bubble sort to sort a set of random numbers. But my code results in a messed up order. For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated. Below is my code.
#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);
int main()
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE];
for (int count = 0; count < MAX_VALUE; count++)
{
numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << numbers[count]<< endl;
sortArray(numbers, count);
showArray(numbers, count);
}
}
void sortArray(int numbers[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (numbers[count] > numbers[count + 1])
{
temp = numbers[count+1];
numbers[count+1] = numbers[count];
numbers[count] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int numbers[], int size)
{
for (int count = 0; count < size; count++)
cout <<numbers[count] << endl;
}
Thanks
The sorting code is correct.
The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.
You should first fill all the data, then sort, then display the sorted result.

Bubble sort, Selection sort, and insertion sort

http://imgur.com/TnUACAc
This is the link that shows the result.
And this result is how my result of C++ must be like
As this result shows, there are Bubble sort, Selection Sort, and Insertion Sort,
and every process of each sort is shown to the black screen.
For example, (Bubble Sort)
20 10 40 30
20 10 30 40
10 20 30 40.
I have to use void displayPtrArray to show like that.
#include <iostream>
#include <string>
#include <array>
#include <iomanip>
using namespace std;
void reset(int array[], const int size);
void displayIntArray();
void displayPtrArray(const int array[], int size);
void BubbleSort(int array[], int size);
void SelectionSort(int array[], int size);
void InsertionSort(int a[], int size);
const int RR = 4;
int main()
{
int arr[RR];
reset(arr, RR);
}
void reset(int array[], const int size)
{
cout << "The originial array has been reset to:" << endl;
int array[RR] = { 20, 40, 10, 30 };
for (int n = 0; n < size; n++)
{
cout << setw(5) << array[n];
}
cout << endl << endl;
}
void displayPtrArray(const int array[], int size)
{
}
void displayIntArray()
{
}
void BubbleSort(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void selectionSort(int array[], int size)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
void InsertionSort(int a[], int size)
{
for (int i = 1; i<size; i++)
{
int j;
int current = a[i];
for (j = i - 1; j >= 0 && a[j]> current; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = current;
}
}
I use the function for every sort, but if that is wrong please tell me.
And teach me how to show the process of each sort with
void displayPtrArray
I really don't know..... T_T...........
PLEASE HELP !!
You already have the exact code you need for displayPtrArray! The for loop defined in reset should do it.
Looking at the expected output, the array gets displayed every time there's a change to it. For bubble sort, the array changes when you do your swap (at the end of the if statement), so you want to add your call to displayPtrArray in the line after swap = true.
For selection sort, the array changes at the end of your outer for loop, so you should add the call to displayPtrArray in the line after array[startScan] = minValue;.
For insertion sort, the array changes at every iteration of the inner for loop and also in the last line of the outer for loop, so you'll probably have to call displayPtrArray in both of those places.
Note: just in case you aren't familiar with the syntax, you call the function like this: displayPtrArray(array, size); where array is the name of your array variable (the name is array in bubble and selection sorts; it's a in insertion sort) and size is the size of the array (named consistently in all three of your sorting functions).
Actually, viewing the process of the sorting is rather simple. You just have to output during the sorting process. You don't need to call another function for that. Try something like this
void BubbleSort(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
cout << "\nThe array is ";
for ( int i = 0; i < ( size - 1 ); i++ )
cout << array[i] << "\t"; // Look here
cout << "\nThe value of temp is " << temp << endl; // and here
}
} while (swap);
}

FirstChance Exception StackOverFlow Merge Sort Shell Sort Bubble Sort

Hey guys I'm working on some sorts and am trying to implement a bubble sort, a merge sort, and a shell sort. I use an outdated technique but I was wondering if you guys could let me know why I keep getting the following error:
First-chance exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
Unhandled exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
I am using Visual Studio 2012 if that plays any part. My code is in three different files so I'll post each separately.
My header file:
#pragma once
class sort
{
public:
sort();
void random1(int array[]);
void random2(int array[]);
void random3(int array[]);
void bubbleSort(int array[], int length);
/*void merge(int *input, int p, int r);
void merge_sort(int *input, int p, int r);*/
void shellSort(int array[], int length);
};
My class implementation file:
#include "sort.h"
#include <time.h>
#include <iostream>
using namespace std;
sort::sort()
{}
void sort::random1(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 25; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random2(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 10000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random3(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 100000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::bubbleSort(int array[], int length)
{
//Bubble sort function
int i,j;
for(i = 0; i < 10; i++)
{
for(j = 0; j < i; j++)
{
if(array[i] > array[j])
{
int temp = array[i]; //swap
array[i] = array[j];
array[j] = temp;
}
}
}
}
/*void sort::merge(int* input, int p, int r) //the merge algorithm of the merge sort
{
int mid = (p + r) / 2;
int i1 = 0;
int i2 = p;
int i3 = mid + 1;
// Temp array
int x = r -p + 1;
int *temp;
temp = new int [x];
// Merge in sorted form the 2 arrays
while ( i2 <= mid && i3 <= r )
if ( input[i2] < input[i3] )
temp[i1++] = input[i2++];
else
temp[i1++] = input[i3++];
// Merge the remaining elements in left array
while ( i2 <= mid )
temp[i1++] = input[i2++];
// Merge the remaining elements in right array
while ( i3 <= r )
temp[i1++] = input[i3++];
// Move from temp array to master array
for ( int i = p; i <= r; i++ )
input[i] = temp[i-p];
}
void sort::merge_sort(int *input, int p, int r) //the merge sort algorithm
{
if ( p < r ) //When p and r are equal the recursion stops and the arrays are then passed to the merge function.
{
int mid = (p + r) / 2;
merge_sort(input, p, mid); //recursively calling the sort function in order to break the arrays down as far as possible
merge_sort(input, mid + 1, r);//recursively calling the sort function in order to break the arrays down as far as possible
merge(input, p, r); //merge function realigns the smaller arrays into bigger arrays until they are all one array again
}
}*/
void sort::shellSort(int array[], int length) //Shell sort algorithm
{
int gap, i, j, temp;
for( gap = length / 2; gap > 0; gap /= 2) //gap is the number of variables to skip when doing the comparisons
{
for( i = gap; i < length; i++) //This for loop sets the variable to use as the gap for the comparisons
{
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap)
{
temp = array[j]; //the array variables are swapped
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}
And my driver file:
#include "sort.h"
#include <iostream>
using namespace std;
int main()
{
int bubbleArray1[25]; //these are the arrays to be sorted. three for each sort. each has a length of 25, 10000, or 100000.
int bubbleArray2[10000];
int bubbleArray3[100000];
int mergeArray1[25];
int mergeArray2[10000];
int mergeArray3[100000];
int shellArray1[25];
int shellArray2[10000];
int shellArray3[100000];
sort Sorts;
Sorts.random1(bubbleArray1);
Sorts.random1(mergeArray1);
Sorts.random1(shellArray1);
Sorts.random2(bubbleArray2);
Sorts.random2(mergeArray2);
Sorts.random2(shellArray2);
Sorts.random3(bubbleArray3);
Sorts.random3(mergeArray3);
Sorts.random3(shellArray3);
cout << "BubbleSort1 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray1, 25);
cout << "BubbleSort2 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray2, 10000);
cout << "BubbleSort3 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray3, 100000);
cout << "End bubble sorts.\n";
/*cout << "MergeSort1 is now being sorted.\n";
Sorts.merge_sort(mergeArray1, 0, 25);
cout << "MergeSort2 is now being sorted.\n";
Sorts.merge_sort(mergeArray2, 0, 10000);
cout << "MergeSort3 is now being sorted.\n";
Sorts.merge_sort(mergeArray3, 0, 100000);
cout << "End merge sorts.\n";*/
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray1, 25);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray2, 10000);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray3, 100000);
cout << "End shell sorts.\n";
cout << "Array\tElements\n";
cout << "BubbleSort1\t";
for(int i = 0; i < 25; i++)
{
cout << bubbleArray1[i] << " ";
}
cout << "\nMergeArray1\t";
for(int i = 0; i < 25; i++)
{
cout << mergeArray1[i] << " ";
}
cout << "\nShellArray1\t";
for(int i = 0; i < 25; i++)
{
cout << shellArray1[i] << " ";
}
return 0;
}
I know it's a lot of code. And there are probably many ways I could make the code better.
I would just like to know what's causing the error up above since I can't find it using my compiler.
You are allocating too much memory on the stack. Variables with 'automatic' storage class go on the stack. Allocate heap instead.
So, instead of:
int shellArray3[100000];
Do:
int* shellArray3 = new int[100000];
Or better yet, use std::vector.
If you don't want to use heap memory, you could also use the static storage class for something like this. To do that:
static int shellArray3[100000];
That will allocate one instance of the variable for the whole program rather than allocating a copy for each function entry on the stack.