给定一个字符串数组,按字典顺序从小到大排序

public class Test {

	public static void main(String[] args) {
		String[] s = { "nba", "cba", "abca", "dba" };
		printArray(s);
		sortArray(s);
		printArray(s);
	}

	// 对字符串数组进行冒泡排序
	public static void sortArray(String[] s) {
		for (int i = 0; i < s.length - 1; i++) {
			for (int j = 0; j < s.length - 1 - i; j++) {
				if ((s[j].compareTo(s[j + 1])) > 0) {
					String temp = s[j];
					s[j] = s[j + 1];
					s[j + 1] = temp;
				}
			}
		}
	}

	// 打印字符数组
	public static void printArray(String[] s) {

		for (int i = 0; i < s.length; i++) {
			System.out.print(s[i] + ",");
		}
		System.out.println();
	}
}

 

你可能感兴趣的:(Java)