#include"arraylist.h"voidarrayInit(structArrayList*array){array->size=8;array->length=0;array->data=malloc(sizeof(void*)*array->size);}voidarrayInitSize(structArrayList*a...
#include "arraylist.h"
void arrayInit(struct ArrayList* array)
{
array->size=8;
array->length=0;
array->data=malloc(sizeof(void *)*array->size);
}
void arrayInitSize(struct ArrayList* array,int size){
array->size=size;
array->length=0;
array->data=malloc(sizeof(void *)*array->size);
}
void arrayExpand(struct ArrayList *array){
void ** tmp=array->data;
array->size=array->size<<1;
array->data=malloc(sizeof(void *)*array->size);
int i=0;
for(i=0;ilength;i++){
array->data[i]=tmp[i];
}
free(tmp);
}
void arrayAdd(struct ArrayList* array,void *pValue){
if(array->lengthsize){
array->data[array->length++]=pValue;
}else{
arrayExpand(array);
arrayAdd(array,pValue);
}
}
void arrayInsert(struct ArrayList* array,int index,void * pValue){
if(array->lengthsize){
int i=0;
for(i=array->length;i>index;i--){
array->data[i]=array->data[i-1];
}
array->data[index]=pValue;
array->length++;
}else{
arrayExpand(array);
arrayInsert(array,index,pValue);
}
}
void arrayRemove(struct ArrayList *array,int index){
void * pValue=array->data[index];
free(pValue);
int i=0;
for(i=index;ilength-1;i++){
array->data[i]=array->data[i+1];
}
array->length--;
}
void arrayRemoveAll(struct ArrayList *array){
int i=0;
for(i=0;ilength-1;i++){
free(array->data[i]);
}
array->length=0;
}
int arrayRemovePValue(struct ArrayList *array,void * pValue){
int count=0;
int i=0;
for(i=0;ilength;i++){
if(array->data[i] == pValue){
count++;
}
array->data[i]=array->data[i+count];
}
free(pValue);
array->length-=count;
return count;
}
int arrayRemoveValue(struct ArrayList *array,void * value,int (*compare)(void * obj1,void *obj2)){
int count=0;
int i=0;
for(i=0;ilength;i++){
if(compare(array->data[i],value)==0){
free(array->data[i]);
count++;
}
array->data[i]=array->data[i+count];
}
array->length-=count;
return count;
}
int arrayBinarySearch(struct ArrayList* array,void * pValue,int (*compare)(void* obj1,void *obj2)){
int low = 0;
int high = array->length - 1;
int mid=-1;
while (low <= high) {
mid = (low + high)/2;
int cmp = compare(array->data[mid],pValue);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
return -1;
}
展开