java 英语字母 排序 汉字全拼 排序 (冒泡排序 & 无递归快排)

来自于论坛:http://topic.csdn.net/u/20100909/15/772e3366-3493-4940-8957-caab9e037418.html


冒泡排序方法:

public static int compare(String s1, String s2) {
    char[] arr1 = s1.toCharArray(), arr2 = s2.toCharArray();
    int index = 0, len1 = arr1.length, len2 = arr2.length;
    int len = len1 < len2 ? len1 : len2;
    while (index < len) {
        char c1 = arr1[index], c2 = arr2[index];
        char c1_ = (char) (c1 >= 'a' ? c1 - ('a' - 'A') : c1);
        char c2_ = (char) (c2 >= 'a' ? c2 - ('a' - 'A') : c2);
        if (c1_ == c2_) {
            if (c1 != c2)
                return c1 - c2;
        } else
            return c1_ - c2_;
        index++;
    }
    if (len1 == len2)
        return 0;
    else if (len1 > len2)
        return arr1[len];
    else
        return -arr2[len];
}

public static void sort(String[] src) {
    String temp;
    for (int i = 0; i < src.length - 1; i++) {
        for (int j = 0; j < src.length - i - 1; j++) {
            if (compare(src[j], src[j + 1]) > 0) {
                temp = src[j];
                src[j] = src[j + 1];
                src[j + 1] = temp;
            }
        }
    }
}

public static void main(String[] args) {
    String[] s = { "Bc", "Ad", "aC", "Hello", "Xman", "little", "During",
            "day" };
    System.out.println("Before sort: " + Arrays.toString(s));
    sort(s);
    System.out.println("After sort: " + Arrays.toString(s));
}

len是s1、s2中较短者的长度,如果能走到这一步,说明两个字符串的前len个字符完全相同
所以这一段代码是对s1是s2的子串或s2是s1的子串的情况下做处理
在这个前提下,如果len1==len2,说明两个字符串的确相同;如果len1len2,那么s2是s1的子串,s1>s2

无递归快排


public static void sort(String[] src) {
    int[][] arr = new int[src.length][2];
    int count = 0, index = 0;
    arr[0][0] = 0;
    arr[0][1] = src.length - 1;
    while (index <= count) {
        int left = arr[index][0];
        int right = arr[index][1];
        int[] dir = { 0, 1 };
        int i = left, j = right;
        String temp;
        while (i < j) {
            if (compare(src[i], src[j]) > 0) {
                temp = src[i];
                src[i] = src[j];
                src[j] = temp;
                dir[0] = 1 - dir[0];
                dir[1] = 1 - dir[1];
            }
            i += dir[0];
            j -= dir[1];
        }
        if (j - left > 1) {
            count++;
            arr[count][0] = left;
            arr[count][1] = j - 1;
        }
        if (right - i > 1) {
            count++;
            arr[count][0] = i + 1;
            arr[count][1] = right;
        }
        index++;
    }
}




你可能感兴趣的:(java,基础,java)