-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort2.java
More file actions
33 lines (31 loc) · 853 Bytes
/
BubbleSort2.java
File metadata and controls
33 lines (31 loc) · 853 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.sort;
/**
* 冒泡排序:执行完一次内for循环后,最大的一个数放到了数组的最后面。相邻位置之间交换
* @author Administrator
*
*/
public class BubbleSort2{
public static void main(String[] args){
int[] a = {3,5,9,4,7,8,6,1,2};
BubbleSort2 bubble = new BubbleSort2();
bubble.bubble(a);
for(int num:a){
System.out.print(num + " ");
}
}
public void bubble(int[] a){
for(int i=a.length-1;i>0;i--){
for(int j=0;j<i;j++){
if(new Integer(a[j]).compareTo(new Integer(a[j+1]))>0){
swap(a,j,j+1);
}
}
}
}
public void swap(int[] a,int x,int y){
int temp;
temp=a[x];
a[x]=a[y];
a[y]=temp;
}
}