第三章:数组[5常见算法]--[9排序]--[冒泡排序]

①图解

 

②实例

public static void bubbleSort(int[] arr){web

       for (int x = 0; x < arr.length - 1; x++) {数组

           for (int y = 0; y < arr.length - 1 - x; y++) {spa

               if (arr[y] > arr[y + 1]) {code

                   int temp = arr[y];orm

                   arr[y] = arr[y + 1];blog

                   arr[y + 1] = temp;排序

               }ci

           }字符串

       }it

}

 

说明:冒泡排序是两两之间进行对比,   如:4.2.5.1.7   :第一次内循环、4和2比-->2,4 、4和5比-->4,五、5和1比-->5,一、5和7比-->5,7。

    这样最大的一个数就到了数组的最后,第二次进行比对的时候只要比数组长度-2次,就是<arr.length-1,便可获得次大的数,放在倒数第二的位置,如此反复获得排序后的数组。

 

③练习

/*

* 把字符串中的字符进行排序。

* 举例:"dacgebf"

* 结果:"abcdefg"

*/

public class ArrayTest {

  public static void main(String[] args) {

       // 定义一个字符串

       String s = "dacgebf";

       // 把字符串转换为字符数组

       char[] chs = s.toCharArray();

       // 把字符数组进行排序

       bubbleSort(chs);

       //把排序后的字符数组转成字符串

       String result = String.valueOf(chs);

       //输出最后的字符串

       System.out.println("result:"+result);

   }

   // 冒泡排序

   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 temp = chs[y];

                   chs[y] = chs[y + 1];

                   chs[y + 1] = temp;

               }

           }

       }

   }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

相关文章
相关标签/搜索