96 lines
2.5 KiB
C++
96 lines
2.5 KiB
C++
#include <iostream>
|
|
using std::cout;
|
|
using std::endl;
|
|
|
|
template <class E> class Storage {
|
|
private:
|
|
E *objectEptr;
|
|
int length;
|
|
void swap(int left, int right) {
|
|
E tmp = objectEptr[left];
|
|
objectEptr[left] = objectEptr[right];
|
|
objectEptr[right] = tmp;
|
|
}
|
|
void quickSort(const int left, const int right) {
|
|
if (left >= right) {
|
|
return;
|
|
}
|
|
int l = left, r = right;
|
|
int pivot = left;
|
|
while (l < r) {
|
|
while (objectEptr[r] >= objectEptr[pivot] && r > l) {
|
|
r--;
|
|
}
|
|
this->swap(pivot, r);
|
|
pivot = r;
|
|
while (objectEptr[l] <= objectEptr[pivot] && l < r) {
|
|
l++;
|
|
}
|
|
this->swap(pivot, l);
|
|
pivot = l;
|
|
}
|
|
this->quickSort(left, pivot - 1);
|
|
this->quickSort(pivot + 1, right);
|
|
}
|
|
|
|
public:
|
|
Storage() : objectEptr(NULL){};
|
|
Storage(const int
|
|
_length) : objectEptr(new E[_length]), length(_length){};
|
|
Storage(const E *originptr, const int _n)
|
|
: objectEptr(new E[_n]), length(_n) {
|
|
for (int i = 0; i < _n; i++) {
|
|
objectEptr[i] = originptr[i];
|
|
}
|
|
};
|
|
~Storage() {
|
|
delete[] objectEptr;
|
|
}
|
|
Storage &sort() {
|
|
quickSort(0, length - 1);
|
|
return *this;
|
|
}
|
|
Storage &sort(const int leftIndex, const int rightIndex) {
|
|
quickSort(leftIndex, rightIndex);
|
|
return *this;
|
|
}
|
|
E *getList() {
|
|
return this->objectEptr;
|
|
}
|
|
int getLength() {
|
|
return this->length;
|
|
}
|
|
Storage &printOut() {
|
|
for (int i = 0; i < this->length; i++) {
|
|
cout << objectEptr[i] << ' ';
|
|
}
|
|
cout << endl;
|
|
return *this;
|
|
}
|
|
E &operator[](int index) {
|
|
return objectEptr[index];
|
|
}
|
|
|
|
int search(E target) {
|
|
for (int i = 0; i < this->length; i++) {
|
|
if (target == objectEptr[i]) {
|
|
return i;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
};
|
|
|
|
int main() {
|
|
int list[6] = {1, 4, 6, 5, 3, 2};
|
|
std::string str = "HelloWorld!";
|
|
Storage<int> aList(list, 6);
|
|
Storage<char> charList(str.c_str(), str.length() + 1);
|
|
aList.printOut().sort().printOut();
|
|
charList.printOut().sort(0, charList.getLength() - 2).printOut();
|
|
aList[2] = 8;
|
|
aList.printOut();
|
|
cout << "8 is at index: " << aList.search(8) << endl;
|
|
cout << "H is at index: " << charList.search('H') << endl;
|
|
return 0;
|
|
} |