三天不练手生,真是这样!下面是代码:
#include
#include
void my_swap(int* a,int* b)
{
int tmp=*a;
*a=*b;
*b=tmp;
}
int my_find(int a[],int length,int target)
{
int i=0;
//defense programming
if(length<=0)
return -1;
while(i
if(a[i]>target)
return i;
i++;
}
return -1;//not found
}
void my_sort(int a[],int length)
{
int i=0,index=0;
if(length<=1) return;
while(i
if(a[i]
index=i;
}
i++;
}
my_swap(a,a+index);
my_sort(a+1,length-1);
}
int p(int n)
{
int i,j,index;//index points to the end of the space
int pivot,trans,result=1;
int* a = (int*)malloc(n*sizeof(int));
if(a==NULL) return -1; //indicated an error
//initial the array
for(i=0;i
a[i]=i;
for(index=0;index
printf("%d ",a[index]);
}
printf("\n");
for(;;){
index=n-1;//every time
while(a[index-1] > a[index]){
if(index <= 1){
free(a);
return result;
}
index--;
}
result++;
pivot = a[index-1];
my_sort(a+index,n-index);
trans = my_find(a+index,n-index,pivot);
if(trans==-1)
return -1;
trans=trans+index;
my_swap(a+index-1,a+trans);
//output the half result to test.
for(index=0;index
printf("%d ",a[index]);
}
printf("\n");
}
}
//framework
int main()
{
int result = p(4);
printf("%d\n",result);
return 0;
}
下面是运行效果:
代码文件名
编译:
gcc -o p
运行
./p
效果截图:
0 1 2 3
0 1 3 2
0 2 1 3
0 2 3 1
0 3 1 2
0 3 2 1
1 0 2 3
1 0 3 2
1 2 0 3
1 2 3 0
1 3 0 2
1 3 2 0
2 0 1 3
2 0 3 1
2 1 0 3
2 1 3 0
2 3 0 1
2 3 1 0
3 0 1 2
3 0 2 1
3 1 0 2
3 1 2 0
3 2 0 1
3 2 1 0
24
;;;;;;;;over