[转载] 【Java】将一个字符串的字符排序,按ASCII表的顺序从小到大
參考鏈接: 在Java中搜索字符串中的字符和子字符串
將一個(gè)字符串的字符按ASCII表的順序從小到大排序,如將字符串“asdafxcvMADb”排序?yàn)椤癆DMaabcdfsvx”
?
?
算法的基本思想: 先將字符串轉(zhuǎn)化為一個(gè)char類型的數(shù)組,來進(jìn)行存儲(因Java中的字符串并不像C++中那樣直接使用數(shù)組存儲)。 之后按照歸并排序的方法,將char數(shù)組中的內(nèi)容按從小到大排序。歸并排序是一種穩(wěn)定的排序算法,而且可以將算法的時(shí)間復(fù)雜度提高到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();? ?//將一個(gè)簡單的字符串中的內(nèi)容轉(zhuǎn)化為char數(shù)組
? ? ? ? sort(array);
? ? ? ? for(char s:array)? ? ? ? ? //輸出
? ? ? ? ? ? System.out.print(s);
? ? }
?
? ? public static void sort(char []arr){
? ? ? ? char []temp = new char[arr.length];? ? //在排序前,先建好一個(gè)長度等于原數(shù)組長度的臨時(shí)數(shù)組,避免遞歸中頻繁開辟空間
? ? ? ? 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);//將兩個(gè)有序子數(shù)組合并操作
? ? ? ? }
? ? }
? ? private static void merge(char[] arr,int left,int mid,int right,char[] temp){
? ? ? ? int i = left;? ? ? ? ? //左序列指針
? ? ? ? int j = mid+1;? ? ? ? //右序列指針
? ? ? ? int t = 0;? ? ? ? ? ?//臨時(shí)數(shù)組指針
? ? ? ? while (i<=mid && j<=right){
? ? ? ? ? ? if(arr[i]<=arr[j])
? ? ? ? ? ? ? ? temp[t++] = arr[i++];
? ? ? ? ? ? else
? ? ? ? ? ? ? ? temp[t++] = arr[j++];
? ? ? ? }
? ? ? ? while(i<=mid){? ? ? ? ? ? ? ?//將左邊剩余元素填充進(jìn)temp中
? ? ? ? ? ? temp[t++] = arr[i++];
? ? ? ? }
? ? ? ? while(j<=right){? ? ? ? ? ? //將右序列剩余元素填充進(jìn)temp中
? ? ? ? ? ? temp[t++] = arr[j++];
? ? ? ? }
? ? ? ? t = 0;
? ? ? ? //將temp中的元素全部拷貝到原數(shù)組中
? ? ? ? while(left <= right){
? ? ? ? ? ? arr[left++] = temp[t++];
? ? ? ? }
? ? }
}
?
?
鑒于代碼中的注釋也比較清楚,這里也不多說。
總結(jié)
以上是生活随笔為你收集整理的[转载] 【Java】将一个字符串的字符排序,按ASCII表的顺序从小到大的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: appium和airtest_关于Air
- 下一篇: c语言 文件游程统计,游程 码表 如何形