package cn.sun;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
/**
* @author JustMonika
* @create 2021-03-06 18:33
*/
public class algorithm {
private int[] arr = new int[100];
@Before
public void before() {
for (int i = 0; i < arr.length; i++) {
arr[i] = new Random().nextInt(100) + 1;
}
}
@Test
public void bubbleSort() {
int count = 0;
boolean flag = false;
System.out.println("排序前:" + Arrays.toString(arr));
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j] ^ arr[j + 1];
arr[j + 1] = arr[j] ^ arr[j + 1];
arr[j] = arr[j] ^ arr[j + 1];
flag = false;
}
count++;
}
if (flag) {
break;
} else {
flag = true;
}
}
System.out.println("排序后:" + Arrays.toString(arr));
System.out.println("总比较次数" + count);
}
}
冒泡排序
最新推荐文章于 2023-06-06 09:14:05 发布