package StringTest; /** * Created by Administrator on 2017/4/18. * 对于数组进行字典排序,遍历所有情况,并且从小到大 */ public class Dictionary { public void diction(String str){ char[] array=str.toCharArray(); dictiona(array); } public void dictiona(char[] array){ shellsort(array,0,array.length-1); int i=0; int j=0; while(true){ if(i<0){ return; } System.out.println(array); for(i=array.length-2;i>=0&&array[i]>array[i+1];i--) { ;} if(i>=0) //注意边界,不确定的时候就加一句if for(j=array.length-1;j>i&&array[j]<array[i];j--){ ; } if(i>=0&&j>=0){ swap(array,i,j); shellsort(array,i+1,array.length-1);} } } public void shellsort(char[] array,int start,int end) { for (int k = (end+1 - start) / 2; k > 0; k = k / 2) { for (int i = 0; i < end+1 - start - k; i++) { if (array[start + i] > array[start + i + k]) { swap(array, start + i + k,start+i); } } } } public void swap(char[] arr,int i,int j){ char temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } public static void main(String[] args) { Dictionary dic=new Dictionary(); dic.diction("acbd"); } }
/*存在的问题: 1.swap函数,当swap函数这样写时,不能达到交换数组元素的目的,不知道为什么? public void swap(char a ,char b){ char temp=a; a=b; b=temp;} char[] arr="abcdefg"; swap(arr[0],ar[1]); System.out.println(arr); //输出结果依然是abcdefg. 这是为什么呢? 2.shellsort函数,必须注意边界值 public void shellsort(char[] array,int start,int end) { for (int k = (end+1 - start) / 2; k > 0; k = k / 2) { //k的取值范围 for (int i = 0; i < end+1 - start - k; i++) { //i 的取值范围 if (array[start + i] > array[start + i + k]) { swap(array, start + i + k,start+i); } } } } //在确定取值范围时,可以列出不等式,比如:start+i+k<=end,所以i<=end-start-k,从而确定了for循环里面i的范围 3.使用for循环时,注意跳出for循环时候的条件 * */
思路:
1,先将数组升序排列
2,打印数组a, 从右到左,找到数列中第一个不是升序数列的a[i]
3,从右到左,找到数列中第一个比a[i]大的数a[j],a[j]与a[i]交换数值
4,将i+1到length-1的数列升序排列(希尔)
5重复到第二步,当i<0的时候跳出循环