考前突击的数据结构基本算法。
KMP:
void Next(char *T,int *next){
int i=1;
next[1]=0;
int j=0;
while(i<strlen(T)){
if(j==0||T[i-1]==T[j-1]){********
i++;
j++;*****************************
next[i]=j;***********************
}
else{
j=next[j];
}
}
}
int KMP(char *S,char *T){
int next[maxsize];
Next(T,next);
int i=1,j=1;**************
while(i<=strlen(S)&&j<=strlen(T)){
if(S[i-1]==T[j-1]||j==0){********
i++;
j++;
}
else{
j=next[j];
}
}
if(j>strlen(T)){
return i-strlen(T);
}
else{
return -1;
}
}
BF:
int index(char *A,char *B){
int i=0,j=0;
while(i<strlen(A)&&j<strlen(B)){
if(A[i]==B[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(B[j]=='\0'){
return i-j;
}
else{
return -1;
}
}
插入排序算法:
void InsertSort(int *A,int n){
int i,j,k;
for(i=1;i<n;i++){
if(A[i]<A[i-1]){
int temp=A[i];
for(j=i-1;temp<A[j];j--){
A[j+1]=A[j];
}
A[j+1]=temp;
}
}
}
快速排序:
int Partition(int A[],int low,int high){
int pivot=A[low];
while(low<high){
while(low<high&&A[high]>pivot){
high--;
}
A[low]=A[high];
while(low<high&&A[low]<pivot){
low++;
}
A[high]=A[low];
}
A[low]=pivot;
return low;
}
void QuickSort(int A[],int low,int high){
if(low<high){
int position=Partition(A,low,high);
QuickSort(A,low,position-1);
QuickSort(A,position+1,high);
}
}
选择排序:
void SelectSort(int a[],int n){
int i,j;
for(i=0;i<n;i++){
int min=i;
for(j=i+1;j<n;j++){
if(a[j]<a[min]){
min=j;
}
}
if(min!=i){
int temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
}
折半插入排序:
void SelectSort(int a[],int n){
int i,j,low,mid,high;
for(i=1;i<n;i++){
int temp=a[i];
low=0,high=i-1;
while(low<=high){
mid=(low+high)/2;
if(a[mid]>temp){
high=mid-1;
}
else{
low=mid+1;
}
}
for(j=i-1;j>=high+1;j--){
a[j+1]=a[j];
}
a[high+1]=temp;
}
}