将字符串数组按照字典顺序排序

public class StringTest1 {

/**
 * 给定一个字符串数组,按照字典顺序进行从小到大的排序
 * {"nba","abc","cba","zz","qq","haha"}
 */
	public static void main(String[] args) {
		String[] arr={"nba","abc","cba","zz","qq","haha"};
		printString(arr);
		System.out.println();
		sortString(arr);
		printString(arr);
		System.out.println();
		sortString1(arr);
		printString(arr);

	}
/**
 * 冒泡排序法
 */
	private static void sortString1(String[] arr) {
		for (int i = 1; i < arr.length; i++) {
			for (int j = 0; j < arr.length-1; j++) {
				if(arr[j].compareTo(arr[j+1])>0){
					swap(arr, j, j+1);
				}
			}
		}
	}

	/**
	 * 选择排序法
	 */
	private static void sortString(String[] arr) {
		
		for (int i = 0; i < arr.length-1; i++) {
			for (int j = i+1; j < arr.length; j++) {
				if (arr[i].compareTo(arr[j])>0) {
					swap(arr,i,j);
				}	
			}
		}
		
	}
	private static void printString(String[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			if (i!=arr.length-1) 
				System.out.print(arr[i]+",");
			else
				System.out.print(arr[i]+"]");
		}
	}

	private static void swap(String[] arr, int i, int j) {
		String temp=arr[i];
		temp=arr[j];
		arr[j]=arr[i];
		arr[i]=temp;
		
	}

}

你可能感兴趣的:(JAVA)