#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
template <class T>
class MyArrayList
{
public:
MyArrayList(int maxSize = 100);
virtual ~MyArrayList();
int getLength() const {return length;}
int getMaxSize() const {return maxSize;}
MyArrayList & addElement(T element); //添加元素
void insertSort(); //插入排序
void outputElements(); //输出元素
void merege(MyArrayList *a1, MyArrayList *a2, MyArrayList *a3); //合并
private:
T* element;
int length;
int maxSize;
};
template <class T>
MyArrayList<T> :: MyArrayList(int maxSize)
{
this->length = 0;
this->maxSize = maxSize;
this->element = new T[this->maxSize];
}
template <class T>
MyArrayList<T> :: ~MyArrayList()
{
delete []element;
}
template <class T>
MyArrayList<T> & MyArrayList<T> :: addElement(T element)
{
if (this->length < maxSize)
{
this->element[this->length++] = element;
}
return *this;
}
template <class T>
void MyArrayList<T> :: outputElements()
{
for (int i = 0; i < this->length; i++)
{
cout << element[i] << "\t";
}
cout << endl;
}
template <class T>
void MyArrayList<T> :: merege(MyArrayList *a1, MyArrayList *a2, MyArrayList *a3)
{
int i = 0;
int j = 0;
int k = 0;
while (i < a1->length && j < a2->length)
{
if (a1->element[i] < a2->element[j])
{
a3->element[k] = a1->element[i];
k++;
i++;
}
else
{
a3->element[k] = a2->element[j];
k++;
j++;
}
}
while (i < a1->length)
{
a3->element[k++] = a1->element[i++];
}
while (j < a2->length)
{
a3->element[k++] = a2->element[j++];
}
a3->length = k - 1;
}
template <class T>
void MyArrayList<T> :: insertSort()
{
for (int i = 1; i < this->length; i++)
{
T data = this->element[i];
int j = i - 1;
while (j > 0 && this->element[j] > data)
{
this->element[j+1] = this->element[j];
j--;
}
this->element[j] = data;
}
}
int main(int argc, char* argv[])
{
srand((unsigned int)time(NULL));
int i = 0;
MyArrayList<int> array1(10);
for (i = 0; i < array1.getMaxSize(); i++)
{
int number = rand() % 50 + 10;
array1.addElement(number);
}
cout << "第一个数组:" << endl;
array1.insertSort();
array1.outputElements();
MyArrayList<int> array2(10);
for (i = 0; i < array1.getMaxSize(); i++)
{
int number = rand() % 50 + 10;
array2.addElement(number);
}
cout << "第二个数组:" << endl;
array2.insertSort();
array2.outputElements();
MyArrayList<int> array3(30);
array3.merege(&array1, &array2, &array3);
cout << "合并数组后:\n";
array3.outputElements();
return 0;
}