i remember reading somewhere in the forum somebody wanted to do a sort from smallest to largest..i did some thinking and made a class for it. i hope it is ok..not the best..but it works..tried it myself. tell me if there is memory leakage or if something is wrong with it
Code:
#include <iostream>
#include <time.h>
using std::cout;
using std::endl;
/*how to use the CBig class
// declares an object of CBig with name x,
// array of size 100 & type int with 100 random values
CBig<int, 100> x;
// sorts the array from smallest to biggest
x.Sort()
// show elements array[0] to array[5] which is 6 elements
x.Show(0, 5);
end of how top use*/
template<class t, int n>
class CBig
{
public:
CBig();
void Sort(); // sort number from smallest to biggest
void Show(int start, int stop);
~CBig() // deletes array and free up memory
{
delete [] array;
}
private:
t* array;
int elements;
// must be private because changes size of array
t GetLowest();
};
// default constructor creates array of size n and of type t
template<class t, int n>
CBig<t, n>::CBig()
{
srand(time(0));
array = new t[n];
elements = n;
for(int i = 0; i < n; i++)
{
array[i] = (rand() % 100 - 1 + 1) + 1;
}
//cout << endl;
}
// function to sort the array from smallest to biggest
template<class t, int n>
void CBig<t, n>::Sort()
{
int max = elements;
t* temp = new t[max];
int index = 0;
for(int i = 0; i < max; i++)
{
temp[i] = GetLowest();
//cout << temp[i] << ' ' << i << endl;
}
delete [] array;
array = new t[max];
elements = max;
for(i = 0; i < elements; i++)
{
array[i] = temp[i];
}
delete [] temp;
}
// show elements from start to stop
template<class t, int n>
void CBig<t, n>::Show(int start, int stop)
{
if((start < 0) || (stop >= elements))
{
cout << "bad range, please try again" << endl;
return;
}
else
{
for(int i = start; i <= stop; i++)
{
cout << i << ") " << array[i] << endl;
}
}
}
// function to GetLowest, can't be called, private member function
template<class t, int n>
t CBig<t, n>::GetLowest()
{
t low = array[0];
int counter = 0;
int index = 0;
for(int i = 0; i < elements; i++)
{
if(low > array[i])
{
low = array[i];
index = i;
}
}
t* temp = new t[elements - 1];
for(i = 0; i < elements; i++)
{
if(i != index)
{
temp[counter++] = array[i];
//cout << temp[--counter] << ' ';
}
}
elements--;
delete [] array;
array = new t[elements];
for(i = 0; i < elements; i++)
{
array[i] = temp[i];
//cout << array[i] << ' ';
}
delete [] temp;
return low;
}