天天看點

java生成随機字元數組并排序

public class test_min {

    public static void main(String[] args) {

        // 求随機字元數組,進行排序

        int a =  (int) (Math.random()*10); //10以内的随機數

        if(a>0) {

            char str[] = new char[a] ;   //随機長度字元數組

            char str1[] = new char[a] ;   //随機長度字元數組

            System.out.println("數組長度為:"+a);

            //給數組指派

            for (int i = 0; i < str.length; i++) {    

                //小寫字元數組

                str[i]  = (char) ((char) (Math.random()*25)+97);                

            }

            for (int i = 0; i < str.length; i++) {    

                //大寫字元數組

                str1[i]  = (char) ((char) (Math.random()*25)+65);

            }

            char temp = 0;

            //排序

            for (int i = 0; i < str.length-1; i++) {                

                for (int j = 0; j < str.length-i-1; j++) {                    

                    if (str[j]>str[j+1]) {                        

                         temp = str[j];

                         str[j] = str[j+1];

                         str[j+1]=temp;                        

                    }                    

                }                

            }

            System.out.println("小寫字元數組排序"+Arrays.toString(str));

            char temp1 = 0;

            for (int i = 0; i < str1.length-1; i++) {                

                for (int j = 0; j < str1.length-i-1; j++) {                    

                    if (str1[j]>str1[j+1]) {                        

                         temp1 = str1[j];

                         str1[j] = str1[j+1];

                         str1[j+1]=temp1;                        

                    }                    

                }                

            }            

            System.out.println("大寫字元數組排序"+Arrays.toString(str1));

        }

    }

}