#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream.h>
#define DATATYPE int
class EasySort{
private:
DATATYPE *data;
int len;
char type;
//below must define by user,in order to test here put it in private
void inline print(DATATYPE);
void inline swap(DATATYPE *,DATATYPE *);
void inline insert(int,int);
int inline compare(const DATATYPE *,const DATATYPE *);
int inline maxOrMin(int,int); //return max/min position order by 'type'
public:
EasySort(DATATYPE *,int,char);
~EasySort();
void show();
void bubbleSort();
void insertSort();
void selectSort();
};
void EasySort::insert(int loc,int ln){
DATATYPE temp=data[ln];
for(int n=ln;n>loc;n--){
data[n]=data[n-1];
}
data[loc]=temp;
}
int inline EasySort::compare(const DATATYPE *a,const DATATYPE *b){
if(*a==*b) return 0;
return *a>*b? 1:-1;
}
void inline EasySort::swap(DATATYPE *a,DATATYPE *b){
DATATYPE c;
c=*a;*a=*b;*b=c;
}
int EasySort::maxOrMin(int beg,int end){
int maxloc;
for(maxloc=--beg;beg<end;beg++)
if(type=='>'){
if(data[maxloc]<data[beg]) maxloc=beg;
}
else{
if(data[maxloc]>data[beg]) maxloc=beg;
}
return maxloc;
}
EasySort::EasySort(DATATYPE *dt,int ln,char c){
data=new DATATYPE[ln];
if(data==NULL) {
perror("create memery error");
return;
}
len=ln;
memcpy(data,dt,ln*sizeof(DATATYPE));
type=c;
}
EasySort::~EasySort(){
delete [] data;
data=NULL;
len=0;
}
void inline EasySort::print(DATATYPE no){
cout<<data[no]<<" ";
}
void EasySort::show(){
cout<<"there are "<<len<<" members"<<endl;
if(type=='>') cout<<"sort by descend"<<endl;
else cout<<"sort by ascend"<<endl;
for(int i=0;i<len;i++)
print(i);
cout<<endl;
}
void EasySort::bubbleSort(){
int n,m,ln,res;
ln=len-1;
for(n=0;n<ln;n++)
for(m=n+1;m<len;m++){
res=compare(data+n,data+m);
if(type=='>'){
if(res==-1) swap(data+n,data+m);
}
else{
if(res==1) swap(data+n,data+m);
}
}
}
void EasySort::selectSort(){
int maxloc,chloc=len-1;
DATATYPE tmp;
for(int n=0;n<len;n++){
maxloc=maxOrMin(1,len-n);
tmp=data[chloc];
data[chloc]=data[maxloc];
data[maxloc]=tmp;
chloc--;
}
}
void EasySort::insertSort(){
for(int n=0;n<len;n++)
for(int m=0;m<n;m++){
if(type=='>'){
if(data[n]>data[m]) insert(m,n);
}
else{
if(data[n]<data[m]) insert(m,n);
}
}
}
void main(){
DATATYPE data[]={2,-4,1,9,6,7,4};
EasySort s(data,sizeof(data)/sizeof(DATATYPE),'>');
s.show();
s.bubbleSort();
//s.insertSort();
//s.selectSort();
s.show();
}