插入排序代码

来源:互联网 发布:淘宝如何授权 编辑:程序博客网 时间:2024/06/04 21:47
 

插入排序的代码,留着以后用。。

template<class T>
void insertionsort(T *Array,int cnt)
{
 T key;
 int j;
 for(int i = 1;i < n;i++)
 {
  key = Array[i];
  j = i - 1;
  while(j >= 0&&key < Array[j])
  {
   Array[j+1] = Array[j];
   j--;
  }
  Array[j +1] = key;
 }
}

 

 

 

全排列问题(第五章问题)


Time Limit:

2000MS

 
Memory Limit:

30000K

Description

输入一个10以内的正整数k,求数字1到k的全排列,按字典序输出。

Input

输入包含多个例子,每个例子含有一个整数k,即是求数字1到k的全排列。输入以0结束

Output

每个例子的输出中,每个排列占据一行。

Sample Input

1

3

0

Sample Output

1

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

Hint

注意输出每行后面没有空格。

Source

常见问题

 

 

全排列的解法。(直接一个一个推)看以后能不能用递归实现。

#include <iostream>
using namespace std;

template<class T>
void insertionsort(T *Array,int cnt)
{
 T key;
 int j;
 for(int i = 1;i < cnt;i++)
 {
  key = Array[i];
  j = i - 1;
  while(j >= 0&&key < Array[j])
  {
   Array[j+1] = Array[j];
   j--;
  }
  Array[j +1] = key;
 }
}

int main()
{
 int indata,j;
 int times = 1;
 int arr[20];
 arr[0] = 100;
 while(1)
 {
  scanf("%d",&indata);
  if(indata)
  {
   for(int i = 1;i <= indata;i++)
   {
    arr[i] = i;
    times *= i;
   } 
   printf("%d",arr[1]);
   for(int i = 2;i <= indata;i++)
   {
    printf(" %d",arr[i]);
   }
   printf("\n");

   //开始排列组合。每次循环输出一个排列组合
   while(1)
   {
    for(j = indata;j >= 1 && arr[j-1] > arr[j];j--);
    if(j >= 1)
    {
     int nMinLarger = arr[j];
     int nMinIdx = j;
     //找出从arr[j]及其后最小的比an【j-1】大的元素,
     //并记下下表
     for(int kk = j; kk <= indata;kk++)
      if(nMinLarger > arr[kk] && arr[kk] > arr[j -1]){
       nMinLarger = arr[kk];
       nMinIdx = kk;
      }
     arr[nMinIdx] = arr[j -1 ];
     arr[j -1] = nMinLarger;
     insertionsort(arr + j, indata - j + 1);
    }
    else
     break;

    printf("%d",arr[1]);
    for(int i = 2;i <= indata;i++)
    {
     printf(" %d",arr[i]);
    }
    printf("\n");
   }

  }
  else break;
 }
 return 0;
}

 

原创粉丝点击