码迷,mamicode.com
首页 > 编程语言 > 详细

java排序之冒泡排序

时间:2018-01-24 22:05:29      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:color   ati   return   mat   冒泡   pac   ini   rgs   col   

代码:

 1 package com.cn.algorithm_arithmetic算法;
 2 /**
 3  * 本程序记录了经典排序算法之冒泡排序
 4  * @author Administrator
 5  *
 6  */
 7 
 8 public class Bubble_Sort {
 9         //冒泡排序优化前
10         public static void bubble_sort(int [] a){
11         for (int i = 0; i < a.length-1; i++) {
12             for (int j = 0; j < a.length-i-1; j++) {
13                 if (a[j+1] < a[j]){
14                     int temp = a[j];
15                     a[j] = a[j+1];
16                     a[j+1] = temp;
17                 }
18             }
19         }
20         }
21         
22         //冒泡排序优化后
23         public static int[] bubble_sort_optimize(int a[]){
24             for (int i = 0; i < a.length-1; i++) {
25                 boolean exchange = false;
26                 for (int j = 0; j < a.length-i-1; j++) {
27                     if (a[j+1]<a[j]){
28                         int tmp = a[j];
29                         a[j] = a[j+1];
30                         a[j+1]=tmp;
31                         exchange = true;
32                     }
33                 
34                 }
35                 if (exchange = false){
36                     break;
37                 }
38             }
39             return a;
40         }
41 
42     public static void main(String[] args) {
43         System.out.println("--------------优化前--------------");
44         System.out.print("冒泡排序优化前原始数据:");
45         int a[] = new int[5];
46         for (int i = 0; i < a.length; i++) {
47             a[i] = (int)(Math.random()*100);
48             System.out.print(a[i]+"  ");
49         }
50         bubble_sort(a);
51         System.out.print("\n冒泡排序优化前新数据:");
52         for (int i = 0; i < a.length; i++) {
53             System.out.print(a[i]+"  ");
54         }
55         System.out.println("\n---------------优化后--------------");
56         //冒泡排序
57         System.out.print("冒泡排序优化后原始数据:");
58         int a1[] = new int[5];
59         for (int i = 0; i < a1.length; i++) {
60             a1[i] = (int)(Math.random()*100);
61             System.out.print(a1[i]+"  ");
62         }
63         bubble_sort_optimize(a1);
64         System.out.print("\n冒泡排序优化后新数据:");
65         for (int i = 0; i < a1.length; i++) {
66             System.out.print(a1[i]+"  ");
67         }
68     }
69 
70 }

冒泡排序的时间复杂度:理想O(n),平均O(n^2),助记口决:外管轮询内管排

java排序之冒泡排序

标签:color   ati   return   mat   冒泡   pac   ini   rgs   col   

原文地址:https://www.cnblogs.com/g177w/p/8343021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!