//直接插入排序,从小到大
void direct_insert(int a[],int n){
int i,j,temp;
for(i=1;i<n;i++){
temp = a[i];//保存待排序元素值
j=i-1;
// while(j>=0&&a[j]>temp){
// a[j+1] =a[j];
// --j;
// }
for(j=i;j>=0&&a[j-1]>temp;--j){
a[j] = a[j-1];
}
a[j] = temp;
}
}
//简单选择排序 ,从小到大
void selectSort(int a[],int n){
int i,j,temp,k;
for(i=0;i<n;i++){
k=i;
for(j=i+1;j<n;j++){
if(a[k]>a[j]){
k=j;
}
}
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
//冒泡排序
void bubbleSort(int a[],int n){
int i,j,temp,flag;
for(i=0;i<n;i++){
flag = 0;
for(j=0;j<n-i-1;j++){
if(a[j]>a[j+1]){
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
flag=1;
}
}
if(flag == 0)break;
}
}
//希尔/增量排序
void shellSort(int a[],int n){
int i,j,temp;
for(int gap = n/2;gap>0;gap/=2){
for(i=gap;i<n;i++){
temp = a[i];
for(j=i;j>=gap&&a[j-gap]>temp;j-=gap){
a[j] = a[j-gap];
}
a[j] = temp;
}
}
}
//快速排序
void quickSort(int a[],int low,int high){
int i,j,temp;
i=low;
j=high;
if(low<high){
temp = a[low];
while(i<j){
while(a[j]>=temp&&i<j)j--;
if(i<j){
a[i] =a[j];
i++;
}
while(a[i]<temp&&i<j)i++;
if(i<j){
a[j] =a[i];
j--;
}
}
a[i] = temp;
quickSort(a,low,i-1);
quickSort(a,i+1,high);
}
}
//堆排序,调整函数sift和主函数heapSort
void sift(int a[],int low,int high){
int i=low;int j=2*i+1;
int temp = a[low];
while(j<=high){
if(j<high&&a[j]<a[j+1]){
j=j+1;
}
if(temp<a[j]){
a[i] = a[j];
i = j;
j = i*2+1;
}
else break;
}
a[i] = temp;
}
void heapSort(int a[],int n){
int i,j;
for(i=n/2-1;i>=0;i--){
sift(a,i,n-1);
}
for(i=n-1;i>0;i--){
j = a[i];
a[i] = a[0];
a[0] = j;
sift(a,0,i-1);
}
}
//归并排序
void merge(int a[],int low,int mid,int high){
int i,j,k;
int n = mid - low+1;
int m = high-mid;
int L[n];
int R[m];
for(i=0;i<n;i++){
L[i] = a[i+low];
}
for(j=0;j<m;j++){
R[j] = a[mid+j+1];
}
i=0;
j=0;
k=low;
while(i<n&&j<m){
if(L[i]<=R[j]){
a[k] = L[i++];
}
else{
a[k] = R[j++];
}
k++;
}
while(i<n){
a[k++] = L[i++];
}
while(j<m){
a[k++] = R[j++];
}
}
void mergSort(int a[],int low,int high){
if(low<high){
int mid = (low+high)/2;
mergSort(a,low,mid);
mergSort(a,mid+1,high);
merge(a,low,mid,high);
}
}
//二叉排序树查找
BTNode* BTNsearch(BTNode* bt,int key){
BTNode* p = bt;
while(p!=NULL){
if(key == p->data){
return p;
}
else if(key>p->data){
p = p->rchild;
}
else{
p = p->lchild;
}
}
}
//二叉排序树递归形式
BTNode* BTNsearch2(BTNode* bt,int key){
BTNode* p = bt;
while(p!=NULL){
if(key == p->data){
return p;
}
else if(key<p->data){
return BTNsearch2(p->lchild,key);
}
else{
return BTNsearch2(p->rchild,key);
}
}
}
//折半查找法
int binarysearch(int a[],int n,int key){
int low = 0;
int high = n-1;
int mid = (low+high)/2;
while(low<=high){
mid = (low+high)/2;
if(a[mid] == key){
return mid;
}
else if(a[mid]<key){
high = mid -1;
}
else{
low = mid+1;
}
}
return -1;
}
排序查找算法代码大全
最新推荐文章于 2023-03-22 11:55:01 发布