二分查找算法(汉诺塔算法),归并排序
二分查找算法(汉诺塔算法)
#include<stdio.h>
#include<stdlib.h>
int pickTopDisk(char *current,char x);
void hanoi(char *current,int n,char A,char B,char C);
int main()
{
char current[]={'A','A','A','A'};
char A='A',B='B',C='C';
hanoi(current,4,A,B,C);
return 0;
}
int pickTopDisk(char *current,char x)
{
int i=0;
while (current[i]!=x)
i++;
return i;
}
void hanoi(char *current,int n,char A,char B,char C)
{
static int count=0;
int i=0;
if(n==1)
{
i=pickTopDisk(current,A);
current[i]=C;
count++;
printf("move %d disk %d: %c->%c\n",count,n,A,C);
return;
}
hanoi(current,n-1,A,C,B);
current[n-1]=C;
count++;
printf("move %d disk %d: %c->%c\n",count,n,A,C);
hanoi(current,n-1,B,A,C);
}
归并排序
#include <stdio.h>
//将有序的SR[i...m]和SR[m+1...n]归并为有序的TR[i...n]
void Merge(int SR[], int TR[], int i, int m, int n)
{
int j,k;
j = m+1;
k = i;
while(i<=m && j<=n)
if(SR[i]<=SR[j])
TR[k++] = SR[i++];
else
TR[k++] = SR[j++];
while(i<=m)
TR[k++] = SR[i++];
while(j<=n)
TR[k++] = SR[j++];
}
//将SR[s...t]归并排序为TR1[s...t]
void MSort(int SR[], int TR1[], int s, int t)
{
int m;
int TR2[10];
if(s == t)
TR1[s] = SR[s];
else
{
m = (s+t)/2; //SR[s...t]平分为SR[s...m]和SR[m+1...t]
MSort(SR,TR2,s,m);//递归地将SR[s...m]归并为有序的TR2[s...m]
MSort(SR,TR2,m+1,t); //递归地将SR[m+1...t]归并为有序的TR2[m+1...t]
Merge(TR2,TR1,s,m,t); //将TR2[s...m]和TR2[m+1...t]归并到TR1[s...t]
}
}
//主函数,调用归并排序MSort
void main()
{int i;
int s[10] = {2,6,7,4,5,10,9,1,3,8};
printf("输出这个数组:\n");
for(i=0;i<10;i++)
printf("%d ",s[i]);
printf("\n");
MSort(s,s,0,9);
printf("输出经过归并排序后的数组:\n");
for(i=0;i<10;i++)
printf("%d ", s[i]);
printf("\n");
}
#include <iostream>
#include <stdlib.h> // srand() 以及 rand()
#include <time.h> // time()
using namespace std;
int partion(int a[],int p,int r){
//rand
srand((unsigned)time( NULL));
int e=rand()%(r-p+1)+p;
int tem;
tem=a[e];
a[e]=a[r];
a[r]=tem;
int x=a[r], i=p-1;
for (int j=p;j<r;j++){
if (a[j]<=x){
tem=a[i+1];
a[i+1]=a[j];
a[j]=tem;
i++;
}
}
tem=a[r];
a[r]=a[i+1];
a[i+1]=tem;
return i+1;
}
void QuickSort(int a[],int p,int r){
if (p<r){
int q=partion(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
int main(){
int array[]={0,-2,11,-4,13,-5,14,-43};
QuickSort(array,0,7);
cout<<"输出这组数"<<endl;
for(int i=0;i<=7;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
return 0;
}