Last active
August 29, 2015 13:57
-
-
Save duyet/9720074 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
typedef enum { | |
tangDan, giamDan | |
} typeSort; | |
class vector { | |
private: | |
int * _array; | |
static const int MAX = 30; | |
int _n, _isSort; | |
public: | |
vector() { | |
_array = new int[MAX]; | |
_n = 0; | |
_isSort = 0; | |
} | |
~vector() { | |
delete [] _array; | |
} | |
int * getAll() { | |
return _array; | |
} | |
bool add(int a) { | |
if (cout() > MAX) { | |
return false; | |
} | |
_n++; | |
_array[_n - 1] = a; | |
return true; | |
} | |
// xoa phan tu tai vi tri a hay la gia tri a? | |
bool remove(int a) { | |
if (_n == 0) return true; | |
for (int i = 0; i < _n; i++) { | |
if (_array[i] == a) { | |
for (int j = i; j < _n; j++) { | |
_array[j] = _array[j+1]; | |
} | |
_n--; i--; | |
} | |
} | |
return true; | |
} | |
int find(int x) { | |
int result = -1; | |
if (_isSort) { | |
result = bin(_array, _n, x); | |
} else { | |
for (int i = 0; i < _n; i++) | |
if (_array[i] == x) result = i; | |
} | |
return result; | |
} | |
int bin(int a[],int n,int x) { | |
int left=0,right=n-1,mid; | |
while(left<right) { | |
mid=(left+right)/2; | |
if(x==a[mid]) | |
return mid; | |
if(x>a[mid]) | |
left=mid+1; | |
if(x<a[mid]) | |
right=mid-1; | |
} | |
return -1; | |
} | |
void swap(int &a, int &b) { | |
a ^= b ^= a ^= b; | |
} | |
void sort(typeSort type) { | |
if (_isSort) return; | |
for (int i = 0; i < _n - 1; i++) { | |
for (int j = i + 1; j < _n; j++) { | |
if (type == tangDan) { | |
if (_array[i] > _array[j]) swap(_array[i], _array[j]); | |
} else { | |
if (_array[i] < _array[j]) swap(_array[i], _array[j]); | |
} | |
} | |
} | |
_isSort = 1; | |
} | |
int cout() { | |
return _n; | |
} | |
bool set(int key, int value) { | |
if (!_array[key - 1]) { | |
return false; | |
} | |
return (_array[key - 1] = value) ? true : false; | |
} | |
int get(int key) { | |
if (key < 1 || key > _n || !_array[key-1]) { | |
throw "None"; | |
} | |
return _array[key - 1]; | |
} | |
}; | |
int main() { | |
vector *v = new vector(); | |
// them phan tu vao mang | |
v->add(5); | |
v->add(10); | |
v->add(8); | |
v->add(11); | |
v->add(20); | |
v->add(3); | |
// xoa phan tu khoi mang | |
v->remove(3); | |
v->remove(5); | |
// tim phan tu trong mang | |
v->find(8); | |
v->find(12); | |
// sap xep mang giam dan | |
v->sort(giamDan); | |
// gan gia tri cho phan tu thu 2 = 111 | |
v->set(2, 111); | |
// lay gia tri phan tu thu 2 gan cho a int | |
int a = v->get(2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment