冒泡排序
冒泡排序是常用的排序方式,规律:(从小到大为例)
1.两个相邻的元素比较大小,大的放到后面。
索引0跟索引1比较,交换位置,接着索引1跟索引2,以此类推。
24 | 23 | 38 | 56 | ... |
0 | 1 | 2 | 3 | ... |
2.每轮元素比较完毕后都会得到一个最大的值,放到了【length-1-第n次的位置】索引上。
3.第一轮比较有0个元素不比较,第二轮比较有1个元素不比较,第三轮有2个元素不比较。。。。
4.总共需要比较数组的长度-1次。
代码实现:
package s20181114;
/**
* @Description: 冒泡排序
* @Author: zhangys
* @CreateDate: 2018/11/14 15:49
* @UpdateUser: zhangys
* @UpdateDate: 2018/11/14 15:49
* @UpdateRemark: 修改内容
* @Version: 1.0
*/
public class BubbleSort {
public static void main(String[] args) {
int[] a = {54,32,48,5,51,58,63,95};
bubbleSort(a);
System.out.println(printArray(a));
}
/**
* 冒泡排序
* @param a
*/
public static void bubbleSort(int[] 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;
}
}
}
}
/**
* 打印数组
* @param a
* @return
*/
public static String printArray(int a[]){
StringBuffer sb = new StringBuffer("【");
for(int i = 0;i<a.length;i++){
if(i == a.length-1){
sb.append(a[i]).append("】");
}else{
sb.append(a[i]).append(", ");
}
}
return sb.toString();
}
}