---
title: "冒泡排序"
author: "sky00768"
date: "2010-09-09T11:09:37Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-09-13T17:38:52Z"
id: 759268
url: "https://sky00768.iteye.com/blog/759268"
---

package sort.bubble;

import java.util.Random;  
/\**  
 * 依次比较相邻的两个数，将小数放在前面，大数放在后面  
 * 冒泡排序，具有稳定性  
 * 时间复杂度为O（n^2）  
 * 不及堆排序，快速排序O（nlogn，底数为2）  
 * @author liangge  
 *  
 \*/  
public class Main {  
 public static void main(String\[] args) {  
  Random ran = new Random();  
  int\[] sort = new int\[10];  
  for(int i = 0 ; i &lt; 10 ; i++){  
   sort\[i] = ran.nextInt(50);  
  }  
  System.out.print("排序前的数组为");  
  for(int i : sort){  
   System.out.print(i+" ");  
  }  
  buddleSort(sort);  
  System.out.println();  
  System.out.print("排序后的数组为");  
  for(int i : sort){  
   System.out.print(i+" ");  
  }  
 }  
   
 /\**  
  * 冒泡排序  
  * @param sort  
  \*/  
 private static void buddleSort(int\[] sort){  
  for(int i=1;i&lt;sort.length;i++){  
   for(int j=0;j&lt;sort.length-i;j++){  
    if(sort\[j]&gt;sort\[j+1]){  
     int temp = sort\[j+1];  
     sort\[j+1] = sort\[j];  
     sort\[j] = temp;  
    }  
   }  
  }  
 }  
}

冒泡排序（BubbleSort）的基本概念是：依次比较相邻的两个数，将小数放在前面，大数放在后面。即首先比较第1个和第2个数，将小数放前，大数放后。然后比较第2个数和第3个数，将小数放前，大数放后，如此继续，直至比较最后两个数，将小数放前，大数放后。重复以上过程，仍从第一对数开始比较（因为可能由于第2个数和第3个数的交换，使得第1个数不再小于第2个数），将小数放前，大数放后，一直比较到最大数前的一对相邻数，将小数放前，大数放后，第二趟结束，在倒数第二个数中得到一个新的最大数。如此下去，直至最终完成排序。