冒泡排序
原理:两层循环,外层冒泡轮数,里层依次比较。
package com.dong.scanner;
import java.util.Arrays;
public class ArrayDemo07 {
public static void main(String[] args) {
int[]a={1,5,8,6,4,2,3,9};
int[]sort= sort(a);
System.out.println(Arrays.toString(sort));
}
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-1-i; j++) {
if (array[j+1]<array[j]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
return array;
}
}
算法时间复杂度为O(n2)
优化
package com.dong.scanner;
import java.util.Arrays;
public class ArrayDemo07 {
public static void main(String[] args) {
int[]a={1,5,8,6,4,2,3,9};
int[]sort= sort(a);
System.out.println(Arrays.toString(sort));
}
public static int[] sort(int[] array){
int temp=0;
for (int i = 0; i <array.length-1 ; i++) {
boolean flag=false;
for (int j = 0; j <array.length-1-i; j++) {
if (array[j+1]<array[j]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
flag=true;
}
}
if(flag==false){
break;
}
}
return array;
}
}
优化的目的是已经排好序的可以不用比较
|