package com.jmdf;
import java.util.Arrays;
/**
* 算法--冒泡排序n个数
* 复杂度-- (((n-1)+1)*(n-1))/2
* 最差 (n²-n)/2
* 最优 1
* O(n²)
*/
public class Algorithm {
public static void main(String[] args) throws Exception {
int[] a =source();
System.out.println();
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
int[] b = sort(a);
result(b);
}
public static int[] source(){
int[] a ={5,4,3,2,1};
System.err.print("冒泡排序前:");
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
for (int i =0;i<a.length;i++){
System.out.print(+a[i]);
}
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
return a;
}
public static int[] sort(int[] sourceArray) throws Exception {
int count =0;//计数交换次数
// 对 arr 进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 1; i < arr.length; i++) {
// 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
System.err.print("交换第"+(++count)+"次数:");
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
for (int t =0;t<arr.length;t++){
System.out.print(+arr[t]);
}
System.out.println();
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
public static int[] result(int[] b){
System.err.print("冒泡排序后:");
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
for (int i =0;i<b.length;i++){
System.out.print(b[i]);
}
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
return b;
}
}
来源:CSDN
作者:开心的小尾叭
链接:https://blog.csdn.net/weixin_39406672/article/details/104476830