冒泡排序
冒泡排序
import java.util.Arrays;
public class arrayDemo7 {
public static void main(String[] args) {
int[] arrays = {5,2,3,1,4,6};
sortArrays(arrays);
System.out.println(Arrays.toString(arrays));
}
public static int[] sortArrays(int[] arrays){
for (int length = arrays.length; length > 0; length--) {
for (int i = 0; i < arrays.length-1; i++) {
int temp = 0;
if(arrays[i] > arrays[i + 1]){
temp = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = temp;
}
}
}
return arrays;
}
}
import java.util.Arrays;
public class arrayDemo8 {
public static void main(String[] args) {
int [] arrays = {2,1,3,45,33,11,7,23};
sortArrays(arrays);
System.out.println(Arrays.toString(arrays));
}
public static int [] sortArrays(int [] arrays){
int temp = 0;
for (int i = 0; i < arrays.length; i++) {
boolean flag = false;//通过flag标识位减少无意义的比较
for (int j =0;j < arrays.length -1-i;j++){
if (arrays[j] > arrays[j + 1]){
temp = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = temp;
flag = true;
}
}
if(flag == false){
break;
}
}
return arrays;
}
}