先附上代码。后面解释。
package tk.javazhangwei.testArray;
/***
* 冒泡排序法
* @author zw
*
*/
public class maopaopaixu {
public static void main(String[] args){
int[] a ={9,3,4,5,2};
FangFa f = new FangFa();
f.ccc(a);
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1-i;j++){
if(a[j]>a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第"+(i+1)+"轮后:");
f.ccc(a);
}
System.out.print("排序后:");
f.ccc(a);
}
}
class FangFa {
public void ccc(int[] a){
for(int k=0;k<a.length;k++){
System.out.print(a[k]+" ");
}
System.out.print("\n");
}
}
运行结果:
如果a[i]>a[j+1],则发生位置交换。否则,位置不用交换
第一轮比较:
- 9和3比较,得出:3 9 4 5 2
- 9和4比较,得出:3 4 9 5 2
- 9和5比较,得出:3 4 5 9 2
- 9和2比较,得出:3 4 5 2 9
第二轮比较:
- 3和4比较,得出:3 4 5 2 9
- 4和5比较,得出:3 4 5 2 9
- 5和2比较,得出:3 4 2 5 9
第三轮比较:
- 3和4比较,得出:3 4 2 5 9
- 4和2比较,得出:3 2 4 5 9
第四轮比较:
- 3和2比较,得出:2 3 4 5 9
最终排序:2 3 4 5 9
#################################
2017年7月25日15:33:00更新
冒泡排序优化版
目的:假定数据有序,后者经过某趟变为有序,减少躺数
package exercise;
/***
* 冒泡排序法(优化版)
* 假定数据有序,后者经过某趟变为有序,减少躺数
* @author zw
*
*/
public class Test01 {
public static void main(String[] args){
int[] a ={1,2,3,5,6};
FangFa f = new FangFa();
f.ccc(a);
Boolean sort = true;
for(int i=0;i<a.length-1;i++){
sort = true;//假定有序
for(int j=0;j<a.length-1-i;j++){
if(a[j]>a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
sort = false;//假定失败
}
if(sort){//减少趟数
break;
}
}
System.out.print("第"+(i+1)+"轮后:");
f.ccc(a);
}
System.out.print("排序后:");
f.ccc(a);
}
}
class FangFa {
public void ccc(int[] a){
for(int k=0;k<a.length;k++){
System.out.print(a[k]+" ");
}
System.out.print("\n");
}
}
#################################
字符串排序方法
package exercise;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/***
* 使用Collections进行排序
* @author zw
*
*/
public class Demo02 {
public static void main(String[] args){
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("a");
list.add("aba");
list.add("abcd");
Collections.sort(list);
System.out.println(list);
}
}