---
title: "组合排序"
author: "Hello-Java"
date: "2012-11-08T10:01:33Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-11-08T10:00:42Z"
id: 1720013
url: "https://hello-jesson.iteye.com/blog/1720013"
---

```
package test1;

public class SortPro {
	
	/**
	 * 题目如下：用1、2、2、3、4、5这六个数字，
	 * 用java写一个main函数，打印出所有不同的排列，
	 * 如：512234、412345等，
	 * 要求："4"不能在第三位，"3"与"5"不能相连
	 */
	//kk表示组合数
	static int kk=0;
	
	//array：传入的字符数组
	//n:表示字符数组的长度
	//k:参数
	 private void zuhe(char[] array, int n, int k) {
	  if (n == k) {
		   if(array[2]!='4'){//第三个位置不能出现4
		    String str = new String(array);
		    if(str.indexOf("53")<0&&str.indexOf("35")<0){//3，5不能连续出现
		    System.out.println(str);
		     ++kk;
		    }
		   }
	  } else {
		   for (int i = k; i < n; i++) {
			//System.out.println("k:"+k);
		    swap(array, k, i);
		    zuhe(array, n, k + 1);
		    swap(array, i, k);  
		   }
	  }
	 }
	 
	 /**功能：数组中下标为x的值与下标为y的值进行互换
	  * @param a：array
	  * @param x:index1
	  * @param y:index2
	  */
	 private void swap(char[] a, int x, int y) {
	  char temp = a[x];
	  a[x] = a[y];
	  a[y] = temp;
	 }
	
	
	public static void main(String[] args) {
		
		  //这里是要用到的所有数组成的一个字符串,其它字符同样适用
		  String s = "122345";
		  char[] c = s.toCharArray();
		  new SortPro().zuhe(c,c.length,0);
		  System.out.println("可能的组合数："+kk);
		
	}
}

```