冒泡排序

来源:互联网 发布:linux增加空间 编辑:程序博客网 时间:2024/06/10 03:14
package testSort;/** *冒泡排序算法  *特点:每趟排序都有一位的排在其最终排列的位置 *冒泡排序算法是稳定的。 *时间复杂度:一般情况下,冒泡排序时间复杂度为O(n^2)。 *冒泡排序最好的情况是:数据的初始序列已经排序,只需要扫描一趟,比较次数为n,没有数据移动,时间复杂度为O(n); *冒泡排序最坏的情况是:数据元素反序排列,需要n-1次扫描,比较次数和移动次数都是O(n^2),时间复杂度为O(n^2); * @author 2萌 * */public class BubbleSort {private void bubbleSort(int[] array) {for (int i = 0; i < array.length; i++) {for (int j = 0; j < array.length-(i+1); j++) {int temp = array[j];while (temp>array[j+1]) {swap(array,j,j+1);}}}}private void swap(int[] array, int j, int i) {int temp = array[i];array[i] = array[j];array[j] = temp;}/** * @param args */public static void main(String[] args) {int[] array = {49,26,97,19,66,8,52};BubbleSort b = new BubbleSort();b.bubbleSort(array);for (int i = 0; i < array.length; i++) {System.out.print(array[i]+"  ");}}}

0 0
原创粉丝点击