冒泡排序
Bubble Sort
1
class ArrayBub
2
{
3
private long[] a;
4
private int nElems;
5
6
public ArrayBub(int max)
7
{
8
a=new long[max];
9
nElems=0;
10
}
11
12
public void insert(long value)
13
{
14
a[nElems]=value;
15
nElems++;
16
}
17
18
public void display()
19
{
20
for(int j=0;j<nElems;j++)
21
System.out.print(a[j]+"");
22
System.out.println("");
23
}
24
25
public void bubblesort()
26
{
27
int out,in;
28
29
for(out=nElems-1;out>0;out--)
30
//针对数组中的最后一个元素,向前推
31
{
32
for(in=0;in<out;in++)
33
//从头开始,把最大的数推到最后一个元素上
34
{
35
if(a[in]>a[in+1])
36
swap(in,in+1);
37
}
38
}
39
}
40
41
public void swap(int one,int two)
42
{
43
long temp=a[one];
44
a[one]=a[two];
45
a[two]=temp;
46
}
47
}
48
49
class ArrayBub2
{3
private long[] a;4
private int nElems;5
6
public ArrayBub(int max)7
{8
a=new long[max];9
nElems=0;10
}11
12
public void insert(long value)13
{14
a[nElems]=value;15
nElems++;16
}17
18
public void display()19
{20
for(int j=0;j<nElems;j++)21
System.out.print(a[j]+"");22
System.out.println("");23
}24
25
public void bubblesort()26
{27
int out,in;28
29
for(out=nElems-1;out>0;out--)30
//针对数组中的最后一个元素,向前推31
{32
for(in=0;in<out;in++)33
//从头开始,把最大的数推到最后一个元素上34
{35
if(a[in]>a[in+1])36
swap(in,in+1);37
}38
}39
}40
41
public void swap(int one,int two)42
{43
long temp=a[one];44
a[one]=a[two];45
a[two]=temp;46
}47
}48
49
附件:java applet 演示
/Files/wenjie/Bubble.rar


浙公网安备 33010602011771号