首页 > 编程语言 > 详细

排序算法之冒泡排序

时间:2017-10-27 12:39:51      阅读:263      评论:0      收藏:0      [点我收藏+]
 1 import java.util.Arrays;
 2 
 3 public class BubbleSort {
 4 
 5     private static int[] intArray = { 100, -2, 56, 65, 46, 488, 145, 666, 555, 71, 0, 1, 65, 68 };
 6 
 7     public static void bubbleSort(int[] intArray) {
 8         for (int i = 0; i < intArray.length - 1; i++) {
 9             for (int j = 0; j < intArray.length - 1 - i; j++) {  
         //j值的范围随着i值增加而减小。外层每一趟循环,较大的元素浮到顶端之前。
10 if (intArray[j] > intArray[j + 1]) { 11 int temp = intArray[j]; 12 intArray[j] = intArray[j + 1]; 13 intArray[j + 1] = temp; 14 } 15 } 16 } 17 System.out.println(Arrays.toString(intArray)); 18 } 19 20 21 public static void main(String[] args) { 22 bubbleSort(intArray); 23 } 24 }

 

//排序后结果:[-2, 0, 1, 46, 56, 65, 65, 68, 71, 100, 145, 488, 555, 666]

  

 

 冒泡排序的基本思想是,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到完全有序。如下图

 

技术分享

 

排序算法之冒泡排序

原文:http://www.cnblogs.com/perkins/p/7742467.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!