Java实现冒泡排序

自从上次写了二分法查找代码后突然打算好好学习一下数据结构.买了一本数据结构与算法......

import java.util.Random; /** * * @author leon.lee */ public class BubbleSort { private int[] arrayData; public void printArrayList(){ if (arrayData!=null){ for(int i:arrayData){ System.out.print(i+","); } System.out.println(""); } } private void swap(int x,int y){ int tempV = arrayData[x]; arrayData[x]=arrayData[y]; arrayData[y]=tempV; } public void sort(){ /* * 如果为了效率则把swap方法直接写在代码里,并且不要使用currentValue和nextValue变量 * 如此写法只是为了让结构清晰,方便阅读 */ for(int i=0;i<arrayData.length;i++){ for(int j=0;j<arrayData.length-i-1;j++){ int currentValue = arrayData[j]; int nextValue = arrayData[j+1]; if(currentValue>nextValue){ swap(j,j+1); } } } } private void initData(){ Random r = new Random(System.currentTimeMillis()); for(int i=0;i<arrayData.length;i++){ arrayData[i]=r.nextInt(100); } } public BubbleSort(int arraylength){ if(arraylength<1){ throw new ExceptionInInitializerError("您不能使用小于1的数字"); }else if(arraylength>100){ throw new ExceptionInInitializerError("您不能使用大于100的数字"); } arrayData = new int[arraylength]; initData(); } public static void main(String[] args) { BubbleSort bs ; try{ bs = new BubbleSort(50); }catch(ExceptionInInitializerError e){ System.out.println(e.getMessage()); return; } bs.printArrayList(); bs.sort(); bs.printArrayList(); } }

 

run:
6,54,18,6,29,85,73,58,91,18,96,24,58,52,49,47,25,52,71,15,63,66,89,79,96,15,64,45,65,64,78,80,56,56,36,72,85,60,80,56,67,67,68,48,28,30,56,1,69,70,
1,6,6,15,15,18,18,24,25,28,29,30,36,45,47,48,49,52,52,54,56,56,56,56,58,58,60,63,64,64,65,66,67,67,68,69,70,71,72,73,78,79,80,80,85,85,89,91,96,96,
成功生成(总时间:1 秒)

 

下面来说一下这种算法的复杂度.

因为操作是在一个嵌套循环里的,所以复杂度为O(N2)

 

类里面的有些方法我写成了protected 为了后面类似的类可以从这里继承

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值