微软Java面试题-按照字母排序
2009-02-21 11:20 乱世文章 阅读(520) 评论(0) 编辑 收藏 举报1.对字符串进行排序,用任意一种编程语言来实现,不能使用现有的类,在排序中,字符串“Bc”,“Ad”,“aC”,“Hello”,“X man”,“little”,“During”,“day”能够排序成 “Ad”,"aC",“Bc”,“During”,“day”,“Hello”,“little”,“Hello”,也就是说,在排序的过程并不是传统的按照字符串排序,在排序中还需要将小写字母一并排序,也就是说a字符串要在B或b之前。
- import java.util.Arrays;
- import java.util.Comparator;
- /**
- * 微软面试题-按照字母排序.<br>
- * 小写字母在大写后面,字母B/b在字母A/a后面<br>
- *
- * @author 老紫竹 JAVA世纪网(java2000.net)
- *
- */
- class T {
- private static final int MASK = 0xFFDF; // 用来把小写变成大写
- public static int compare(String o1, String o2) {
- int length1 = o1.length();
- int length2 = o2.length();
- int length = length1 > length2 ? length2 : length1;
- int c1, c2;
- int d1, d2;
- for (int i = 0; i < length; i++) {
- c1 = o1.charAt(i);
- c2 = o2.charAt(i);
- d1 = c1 & MASK;
- d2 = c2 & MASK;
- if (d1 > d2) {
- return 1;
- } else if (d1 < d2) {
- return -1;
- } else {
- if (c1 > c2) {
- return 1;
- } else if (c1 < c2) {
- return -1;
- }
- }
- }
- if (length1 > length2) {
- return 1;
- } else if (length1 < length2) {
- return -1;
- }
- return 0;
- }
- public static void sortByPOPO(String[] args) {
- String tmp;
- for (int i = 0; i < args.length; i++) {
- for (int j = i + 1; j < args.length; j++) {
- if (compare(args[i], args[j]) > 0) {
- tmp = args[i];
- args[i] = args[j];
- args[j] = tmp;
- }
- }
- }
- // [Ad, aC, Bc, During, day, Hello, little, X man]
- System.out.println(Arrays.toString(args));
- }
- public static void main(String[] args) {
- String[] strs = { "Bc", "Ad", "aC", "Hello", "X man", "little", "During",
- "day" };
- sortByPOPO(strs);
- }
- }