字符串的排序问题--长度+字典序

问题:对字符串排序,先保证长度,然后在长度相同的情况下保证字典序最小;

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
char a[][5]={"12","13","123","1234","21","34"};
int n=6;
void len_sort(){
	for(int i=0;i<n;i++)
		for(int j=i+1;j<n;j++)
			if(strlen(a[i])>strlen(a[j]))//先按照长度排序 
				swap(a[i],a[j]);
//	for(int i=0;i<n;i++)
	//	printf("--->>>%s\n",a[i]);	
	for(int i=0;i<n;i++)
		for(int j=i+1;j<n;j++)
			if(strlen(a[i])==strlen(a[j])&&strcmp(a[i],a[j])>=0)//在长度相同的情况下字典序排序 
				swap(a[i],a[j]);
	for(int i=0;i<n;i++)
		printf("--->>>%s\n",a[i]);	
}
int main(){
	len_sort();
}

程序运行结果:

--->>>12
--->>>13
--->>>21
--->>>34
--->>>123
--->>>1234

--------------------------------
Process exited after 2.702 seconds with return value 0
请按任意键继续. . .
发布了226 篇原创文章 · 获赞 90 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/105287868