Hey guys, I was wondering if you guys could take a look at my code. I am trying to simply implement Bubble Sort, but I am having trouble getting it to compile. I managed to get it to compile and run successfully just using functions in my main file, but when I put my functions into a class and try and run it from a class file. I keep getting these errors:
#include <iostream>
#include "BubbleSort.h"
usingnamespace std;
constint MAX = 10; //the maximum number of elements that the array can hold
int main()
{
int b[MAX];
BubbleSort sort;
sort.RandomArray(b);
sort.PrintSort(b, MAX);
sort.B_Sort(b, MAX);
sort.PrintSort(b, MAX);
return 0;
}
BUBBLESORT.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef BUBBLESORT_H
#define BUBBLESORT_H
#include <cstdlib>
usingnamespace std;
class BubbleSort{
public:
void RandomArray(int a[]); //This function will generate random integers in array
void B_Sort(int a[], int length); //This function will implement BubbleSort Algo
void PrintSort(int a[], int length); //This function will print out Array
};//End BubbleSort Class
#endif /* BUBBLESORT_H */
#include "BubbleSort.h"
void BubbleSort::RandomArray(int a[])
{
int i;
srand(time(0)); //seeds, so that a new algorithm can be used for rand()
for(i = 0; i < MAX; i++)
a[i] = rand() % 100; //this generates a random number from 0 - 100
}//End RandomArray
void BubbleSort::B_Sort(int a[], int length)
{
int i, j, temp;
for(i = 0; i < length; i++)
{
for(j = 0; j < i; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j]; //This switches elements in Bubble Sort
a[j] = temp;
}
}
}
}//End B_Sort
void BubbleSort::PrintSort(int a[], int length)
{
int i;
for(i = 0; i < length; i++)
cout << a[i] << ", ";
cout << endl << endl;
}//End PrintSort
No this is not homework, I'm trying to get a feel for different data structures so that I can start building myself a professional portfolio. Thanks in advance
You didn't include BUBBLESORT.cpp in your project.
And you don't need <cstdlib> in BUBBLESORT.h. Put it in BUBBLESORT.cpp instead.
And never, NEVER put usingnamespace std; in headers. This will make everyone using you library want to brutally murded you.
#include directive executed by preprocessor and basically means "copy-paste all content of <> file here" As you can see there is no way to tell which file should be included to your project. Actually you don't need to name you cpp file accordingly to .h file. You can have 2 cpp files for one .h file or one cpp for two .h.
More: you can compile main.cpp and bubblesort.cpp on two different computers and link them on third, but it is advanced topic :)