- package cn.itcast_03;
- /*将字符串进行排序
- * 举例:"dacgebf"
- * 结果:"abcdefg"
- * 分析:
- * A:定义一个字符串
- * B:将字符串转化为字符数组
- * C:将字符数组用冒泡和选择排序进行排序
- * D:将字符数组转化为字符串(注意:如果不转化直接输出,呈现的结果虽然还是abcde,但意义却不一样)
- * E:输出字符串
- */
- public class ArrayTest {
- public static void main(String[] args) {
- String s = "dacgebf";
- char[] chs = s.toCharArray();
- bubbleSort(chs);
- String result =String.valueOf(chs);//方式1:调String方法
- System.out.println("result:"+result);
- selectSort(chs);
- String result1 = new String(chs);//方式2:构造方法转化为字符串
- System.out.println("result1:"+result);
-
-
- }
-
- public static void selectSort(char[] chs) {
- for (int x=0;x<chs.length-1;x++) {
- for (int y=x+1;y<chs.length;y++) {
- if (chs[y]<chs[x]) {
- char tempt = chs[x];
- chs[x] = chs[y];
- chs[y] = tempt;
- }
- }
- }
-
- }
- public static void bubbleSort(char[] chs) {
- for (int x=0;x<chs.length-1;x++) {
- for (int y=0;y<chs.length-1-x;y++){
- if (chs[y]>chs[y+1]) {
- char tempt = chs[y];
- chs[y] = chs[y+1];
- chs[y+1] = tempt;
- }
-
- }
- }
-
- }
- }
复制代码
|
|