一.冒泡排序
/**
* 冒泡排序
* 冒泡排序总的平均时间复杂度为:O(n2) On的平方,空间复杂度 O(n)
* 优化部分是判断是否已经为有序,若有序那么结束排序
*/
public class BubbleSort {
public static void main(String[] args){
int[] intList = {1,2,4,3,5,0,8,69,70,53};
bubbleSort(intList);
}
//排序
static void bubbleSort(int[] intList){
int temp = 0;
for(int i=0;i<intList.length;i++){
Boolean sort = true; //优化部分
for(int j=0;j<intList.length-i-1;j++){
if (intList[j] > intList[j+1]){
temp =intList[j];
intList[j] = intList[j+1];
intList[j+1] = temp;
sort = false; //优化部分
}
}
if (sort) break; //优化部分
}
System.out.println(Arrays.toString(intList));
}
//优化算法二
static int[] bubblesort(int[] arr){
for(int end = arr.length-1;end>0;end--){
int sortedIndex = 1;
for(int begin=1;begin<=end;begin++){
if (arr[begin-1]>arr[begin]){
int tmp = arr[begin-1];
arr[begin-1] = arr[begin];
arr[begin] = tmp;
sortedIndex = begin;
}
}
end = sortedIndex;
}
return arr;
}
}