需求
冒泡排序,把数组从小到大进行排列
思路总结
- 冒泡排序采用双循环,i循环代表要排序几趟,j循环代表一趟要排序几次;
- 有n个数要排 n-1趟,一趟n-i次(因为前面排过的数字不必再排);
- 冒泡排序算法思路图(bubble):
代码实现
package com.jichu.Arry;
import java.util.Arrays;
public class Demo06 {
public static void main(String[] args) {
int[] a ={ 54,46,12,32,44,11,0,3};
int[] b = sort(a);
System.out.println(Arrays.toString(b));
}
//冒泡排序
public static int[] sort(int[] array){
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {//几趟
for(int j = 0; j <array.length - i - 1; j++) {//一趟交换几次
if(array[j] > array[j+1]){//从小到大
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
return array;
}
}