(需要包含<string.h>头文件)
char t,s[200]
int i,i
gets(s)
for(i=0i<strlen(s)-1i++)
for(j=0j<strlen(s)-1-ij++)
if(s[j]>s[j+1])
{t=s[j]s[j]=s[j+1]s[j+1]=t}
puts(s)
c语言字符排序:输入:abc 输出:abc acb bac bca cab cba
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void mySwap(char *a,char *b)
{
char temp
temp = *a
*a = *b
*b = temp
}
void PaiLie(char *list,int begin,int end)
{
int i
if(list == NULL)
return
if(begin == end)
{
printf("%s ",list)
printf("\n")
}else{
for(i = begin i<=end i++)
{
mySwap(&list[i],&list[begin])
PaiLie(list,begin+1,end)
mySwap(&list[i],&list[begin])
}
}
}
void main()
{
char list[] = "abc"
char out [4]
PaiLie(list,0,2)
//ZuHe(list,out,3,0,0)
}
如果有重复,去掉重复的,然后满足一些特定的要求(如:第3个位置不可以是4,3和5不可以相邻)
Java实现。
此方法需要输入数字从小到大排列,若不是只需在排列之前预处理一下即可。
关键是compareTo方法
[java] view plain copy
package dataStruct
import java.util.LinkedList
import java.util.List
public class PaiLie {
private static List<String>result = new LinkedList<String>()
private static String lastResult = ""
public static void main(String[] args) {
String s = "1223"
char[] c = s.toCharArray()
paiLie(c, 0, c.length - 1)
for (int i = 0i <result.size()i++)
System.out.println(result.get(i))
}
public static boolean validator(String s) {
if (s.compareTo(lastResult) <= 0) //去重复的关键
return false
if (s.charAt(2) == '4')
return false
if (s.indexOf("35") >= 0)
return false
if (s.indexOf("53") >= 0)
return false
return true
}
public static void paiLie(char[] c, int begin, int end) {
if (begin == end) {
String s = new String(c)
if (validator(s)) {
lastResult = s
result.add(s)
}
}
for (int i = begini <= endi++) {
swap(c, begin, i)
paiLie(c, begin + 1, end)
swap(c, begin, i)
}
}
public static void swap(char[] c, int i, int j) {
char temp
temp = c[i]
c[i] = c[j]
c[j] = temp
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)