參考鏈接: 在Java中搜索字符串中的字符和子字符串
將一個字符串的字符按ASCII表的順序從小到大排序,如將字符串“asdafxcvMADb”排序為“ADMaabcdfsvx”
?
?
算法的基本思想: 先將字符串轉化為一個char類型的數組,來進行存儲(因Java中的字符串并不像C++中那樣直接使用數組存儲)。 之后按照歸并排序的方法,將char數組中的內容按從小到大排序。歸并排序是一種穩定的排序算法,而且可以將算法的時間復雜度提高到O(nlgn)。?
廢話不多說,直接上代碼:?
public class Demo {
? ? public static void main(String[] args){
? ? ? ? Demo demo=new Demo();
? ? ? ? String string="asdafxcvMADb";
? ? ? ? demo.sortByASCII(string);
? ? }
?
? ? public void sortByASCII(String str){
? ? ? ? char []array=str.toCharArray();? ?//將一個簡單的字符串中的內容轉化為char數組
? ? ? ? sort(array);
? ? ? ? for(char s:array)? ? ? ? ? //輸出
? ? ? ? ? ? System.out.print(s);
? ? }
?
? ? public static void sort(char []arr){
? ? ? ? char []temp = new char[arr.length];? ? //在排序前,先建好一個長度等于原數組長度的臨時數組,避免遞歸中頻繁開辟空間
? ? ? ? sort(arr,0,arr.length-1,temp);
? ? }
? ? private static void sort(char[] arr,int left,int right,char []temp){
? ? ? ? if(left<right){
? ? ? ? ? ? int mid = (left+right)/2;
? ? ? ? ? ? //遞歸的方法
? ? ? ? ? ? sort(arr,left,mid,temp);? ? ? ? //左邊歸并排序,使得左子序列有序
? ? ? ? ? ? sort(arr,mid+1,right,temp);//右邊歸并排序,使得右子序列有序
? ? ? ? ? ? merge(arr,left,mid,right,temp);//將兩個有序子數組合并操作
? ? ? ? }
? ? }
? ? private static void merge(char[] arr,int left,int mid,int right,char[] temp){
? ? ? ? int i = left;? ? ? ? ? //左序列指針
? ? ? ? int j = mid+1;? ? ? ? //右序列指針
? ? ? ? int t = 0;? ? ? ? ? ?//臨時數組指針
? ? ? ? while (i<=mid && j<=right){
? ? ? ? ? ? if(arr[i]<=arr[j])
? ? ? ? ? ? ? ? temp[t++] = arr[i++];
? ? ? ? ? ? else
? ? ? ? ? ? ? ? temp[t++] = arr[j++];
? ? ? ? }
? ? ? ? while(i<=mid){? ? ? ? ? ? ? ?//將左邊剩余元素填充進temp中
? ? ? ? ? ? temp[t++] = arr[i++];
? ? ? ? }
? ? ? ? while(j<=right){? ? ? ? ? ? //將右序列剩余元素填充進temp中
? ? ? ? ? ? temp[t++] = arr[j++];
? ? ? ? }
? ? ? ? t = 0;
? ? ? ? //將temp中的元素全部拷貝到原數組中
? ? ? ? while(left <= right){
? ? ? ? ? ? arr[left++] = temp[t++];
? ? ? ? }
? ? }
}
?
?
鑒于代碼中的注釋也比較清楚,這里也不多說。