题目要求:随机产生70个字符放在一个数组里,字符只能是数字或英文字母(一共62个字符),然后用程序将它们重新排序并打印出来。
优先排序规则:数字最优先,字母按照字母表顺序,比如 a 优先于 b 打印,但大写字母优先于小写字母!
排序算法用快排,成员比较直接用字符串比较就行。
因为你的排序规则和字符的Ascii大小本来就是一致的:
字符 Ascii
---- --------
0~9 48~ 57
A~Z 65~ 90
a~z 97~122
建一个数组或者hash map,然后记录下每个key的个数,然后按照key的顺序打印就好了。
比如说:
a, 1, b, a, 3, 2, 1, b, a.
建一个hash map,左边是key,有边是key出现的次数:
1:2
2:1
3:1
a:3
b:2
排序结果就是
1, 1, 2, 3, a, a, a, b, b. 复杂度是o(n)
#include
#include
#define MAX 70
#define BIG 62
int temp[BIG];
void main()
{
int arr[MAX];
int i=0,j=0;
for (i=0; i<MAX; i++)
{
arr[i] = rand()%BIG;
}
printf("随机得到的数值数组如下:\n");
for (i=0; i<MAX; i++)
{
if (arr[i] >= 10 && arr[i] < 36)
printf(" %c",'A'+arr[i]-10);
else if (arr[i] >= 36)
printf(" %c",'a'+arr[i]-36);
else printf(" %c",'0'+arr[i]);
}
printf("\n\n");
for (i=0; i<MAX; i++)
{
temp[arr[i]]++;
}
for (i=0; j<MAX; i++)
{
fuwei:
if (temp[i] > 0)
{
arr[j++] = i;
temp[i]--;
goto
fuwei;
}
}
printf("经过排序后数值数组如下:\n");
for (i=0; i<MAX; i++)
{
if (arr[i] >= 10 && arr[i] < 36)
printf(" %c",'A'+arr[i]-10);
else if (arr[i] >= 36)
printf(" %c",'a'+arr[i]-36);
else printf(" %c",'0'+arr[i]);
}
system("pause");
}
题主若有疑问的话,请私信我,谢谢!
我用的是java语言,排序算法直接使用java提供的方法即可。耗时1毫秒。
import java.util.Arrays;
import java.util.Random;
public class SortDemo {
public static void main(String[] args) {
long l = System.currentTimeMillis();
char[] srcChars = getChars(70);
System.out.print("排序前:");
System.out.println(srcChars);
// 排序
Arrays.sort(srcChars);
System.out.print("排序后:");
System.out.println(srcChars);
System.out.println("耗时:" + (System.currentTimeMillis() - l) + "毫秒");
}
/**
* 随机获取一个长度为num的字符串,只能是数字或字母
*
* @param num
* @return
*/
private static char[] getChars(int num) {
char[] result = new char[num];
int index = 0;
Random random = new Random();
for (int i = 0; i < result.length; i++) {
index = random.nextInt(62);
result[i] = getChar(index);
}
return result;
}
/**
* 根据随机值index获取对应的字母<br>
* 0-9对应数字0-9(ascii值为48-57)<br>
* 10-35对应大写字母A-Z(ascii值为65-90)<br>
* 36-61对应小写字母a-z(ascii值为97-122)<br>
*
* @param index
* @return
*/
private static char getChar(int index) {
if (index >= 0 && index <= 9) {
index += 48;
} else if (index >= 10 && index <= 35) {
index += 55;
} else {
index += 61;
}
return (char) index;
}
}
运行结果:
排序前:jVQk1J4XyMABTVpOVitAeOSyC9PH3svcr2xoPAMfpuvIZkya4SRJ8ckUa1bNVUdxoVHuyL
排序后:11234489AAABCHHIJJLMMNOOPPQRSSTUUVVVVVXZaabccdefijkkkoopprstuuvvxxyyyy
耗时:1毫秒