排序算法:冒泡
基本思想:
- 从前往后,依次比较相邻两个元素的大小,如果前一个比后一个大,就交换位置;
- 每一趟冒泡排序,都会将大的元素往最后的位置移动,每一趟要经过(n-已经排序的元素个数)个元素,一共要经过n-1趟。所以时间复杂度为:O(n²)
示例代码:
public class BubbleSort {
private static int[] arr = {5, -8, 6, 25, -74, 10, 0, 4};//8
public static void main(String[] args) {
for (int i = 0; i < arr.length; i++){//控制循环的次数
for (int j = 0; j < arr.length-1-i; j++){//数组的索引
if (arr[j] > arr[j+1]){
int temp = 0;//如果前一个数比后一个数大,就交换位置
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int a : arr){
System.out.println(a);
}
}
}
优化:
例子:{1,2,3,4,5,6,7,8,10,9}对于像这种数组,当第一次排序之后数组就已经是有序的了,所以剩下的八次都是无效操作。针对这种情况可以做出优化:在排序的时候加入标记,如果某一趟没有交换元素,那就说明数组已经是有序的了
改进代码:
public class BubbleSort {
private static int[] arr = {5, -8, 6, 25, -74, 10, 0, 4};//8
public static void main(String[] args) {
for (int i = 0; i < arr.length; i++){//控制循环的次数
int flag = 0;
for (int j = 0; j < arr.length-1-i; j++){//数组的索引
if (arr[j] > arr[j+1]){
int temp = 0;//如果前一个数比后一个数大,就交换位置
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = 1;
}
}
if (flag == 0) break;
}
for (int a : arr){
System.out.println(a);
}
}
}
继续优化:上一步的优化仅仅适用于连片有序而整体无序的数据(例如:1,2,3,4,5,6,7,8,10,9)。但是对于前面大部分是无序而后边小半部分有序的数据(1,2,5,7,4,3,6,8,9,10)排序效率也不可观,对于种类型数据,我们可以继续优化。既可以记下每一次交换的位置,如果后边没有交换,必然是有序的,然后下一次排序从第一个比较到上次记录的位置结束即可。
改进代码:
public class BubbleSort {
private static int[] arr = {5, -8, 6, 25, -74, 10, 0, 4};//8
private static int flag = 0;//记录是否交换的标记
private static int loc = arr.length-1;//记录交换位置的标记
private static int pos = 0;//临时存储最后一次的标记位
public static void main(String[] args) {
for (int i = 0; i < arr.length; i++){//控制循环的次数
for (int j = 0; j < loc; j++){//数组的索引
if (arr[j] > arr[j+1]){
int temp = 0;//如果前一个数比后一个数大,就交换位置
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = 1;
pos = j;
}
}
loc = pos;
if (flag == 0) break;
}
for (int a : arr){
System.out.println(a);
}
}
}