目录
1、冒泡排序
(1)依次比较数组中相邻两个元素的大小,若a[i] > a[i+1],则交换两个元素,结果是让最大的元素排至最后
(2)重复以上步骤,直到整个数组有序
2、代码实现
public class BubbleSort {
public static void main(String[] args) {
int[] a = {5,9,7,4,1,3,2,8};
bubble(a);
}
public static void bubble(int[] a){
for (int j = 0; j < a.length - 1; j++) {
//一轮冒泡
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
}
}
System.out.println("第"+j+"轮冒泡"+Arrays.toString(a));
}
}
public static void swap(int[] a,int i,int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
3、冒泡排序优化
(1)减少比较次数
public class BubbleSort {
public static void main(String[] args) {
int[] a = {5,9,7,4,1,3,2,8};
bubble(a);
}
public static void bubble(int[] a){
for (int j = 0; j < a.length - 1; j++) {
//一轮冒泡
for (int i = 0; i < a.length - 1 -j; i++) { // a.length - 1 -j 减少冒泡比较次数
System.out.println("比较次数:"+i);
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
}
}
System.out.println("第"+j+"轮冒泡"+Arrays.toString(a));
}
}
public static void swap(int[] a,int i,int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
(2)减少冒泡次数
public class BubbleSort {
public static void main(String[] args) {
int[] a = {5,9,7,4,1,3,2,8};
bubble(a);
}
public static void bubble(int[] a){
for (int j = 0; j < a.length - 1; j++) {
//一轮冒泡
boolean swapped = false; // 是否发生了交换
for (int i = 0; i < a.length - 1 -j; i++) { // a.length - 1 -j 减少冒泡比较次数
System.out.println("比较次数:"+i);
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
swapped = true;
}
}
System.out.println("第"+j+"轮冒泡"+Arrays.toString(a));
if (!swapped){
break;
}
}
}
public static void swap(int[] a,int i,int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
(3)进一步优化比较次数
public class BubbleSort {
public static void main(String[] args) {
int[] a = {5,2,7,4,1,3,8,9};
bubble2(a);
}
public static void bubble2(int[] a){
int n = a.length - 1;
while (true) {
int last = 0;
for (int i = 0; i < n; i++) {
System.out.println("比较次数:"+i);
if (a[i] > a[i+1]){
swap(a,i,i+1);
last = i;
}
}
n = last;
System.out.println("第轮冒泡"+Arrays.toString(a));
if (n == 0){
break;
}
}
}
public static void swap(int[] a,int i,int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
4、优化方式
每轮冒泡时,最后一次交换索引可以作为下一轮冒泡的比较次数,如果这个值为零,表示整个数组有序,直接退出外层循环即可