import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* 冒泡排序
*/
public class BubbleSort {
/**
* 冒泡排序
* @param array
*/
public static void sort(int[] array) {
for (int time = 1; time < array.length; time++) {
for (int j = 0; j < array.length - time; j++) {
if (array[j] > array[j + 1]) {
swap(array, j , j + 1);
}
}
}
}
/**
* 元素交换
* @param array
* @param i
* @param j
*/
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
int[] array = generateArray(10);
System.out.println("Original: " + Arrays.toString(array));
sort(array);
System.out.println("After Sort: " + Arrays.toString(array));
}
/**
* 生成随机数组
* @param length
* @return
*/
private static int[] generateArray(int length) {
Random random = new Random(31);
int[] array = new int[length];
Set<Integer> set = new HashSet<>(length);
for (int i = 0; i < length; i++) {
int value;
do {
value = random.nextInt(length);
} while (set.contains(value));
array[i] = value;
set.add(value);
}
return array;
}
}
排序 - 冒泡排序
最新推荐文章于 2024-09-03 18:29:17 发布