字典排序算法的实现

来源:互联网 发布:数据库管理系统的发展 编辑:程序博客网 时间:2024/05/05 00:09

  字典排序算法:

           有一序列:p1 p2 p3.....pn,共有排序结果int count=n*(n-1)*.....*2*1;一下循环count-1次

            1.找出  m=max{i| pi-1<pi}

            2.找出  k=max{j|pm-1<pj}

             3.交换pm-1  与  pk

             4  将pm.....pn 的次序颠倒

           

 

/***
  author:zhangrong
  date:2013/4/17
  实现字典排列顺序
*/
#include<iostream>
#include<cstdio>
#include<stack>
#define NUM   11
using namespace std;

int map[NUM];

int main()
{
 int i,j,k;
 int len;
 stack<int>  sta;
 cin>>len;
 for(i=0;i<len;i++)
  map[i]=i;
 for(k=0;k<len;k++)
  cout<<map[k];
 cout<<"\t";
 int count=1;
 for(int i=2;i<=len;i++)
  count*=i;
 for(i=1;i<count;i++)
 {
  j=0;
  int m=0,n,w;
  for(k=1;k<len;k++)
   if(map[k]>map[k-1])m=k;
  n=m-1;
  w=-1;
  for(k=0;k<len;k++)
   if(map[n]<map[k]&&k>w)w=k;
  int temp=map[n];
  map[n]=map[w];
  map[w]=temp;
  for(k=m;k<len;k++)
   sta.push(map[k]);
  for(k=m;k<len;k++)
  {
   map[k]=sta.top();
   sta.pop();
  }
  for(k=0;k<len;k++)
   cout<<map[k];
  cout<<"\t";


 }
}