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

①图解

 

②实例

public static void bubbleSort(int[] arr){

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

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

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

                   int temp = arr[y];

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

                   arr[y + 1] = temp;

               }

           }

       }

}

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

               }

           }

       }

   }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/Lucky-stars/p/11010219.html