java利用随机数生成数组进行冒泡排序
import java.util.Random;
public class BubbleSort{
public static void main(String[] args){
int[] ints = arrGet(20, 100,0);
bubbleSort(ints);
}
/**
*
* @param ArrLength 数组的长度
* @param RandLength 随机数的取值范围
* @param p 1为打印生成的数组值
* @return
*/
public static int[] arrGet(int ArrLength, int RandLength, int p) {
int[] x = new int[ArrLength];
for (int i=0;i < x.length;i++){
int nextInt = new Random().nextInt(RandLength);
x[i] = nextInt;
}
if (p == 1){
printArray(x);
}
return x;
}
/**
* 打印数组程序
* @param arr
*/
public static void printArray(int[] arr) {
for (int y = 0; y < arr.length; y++) {
System.out.print(arr[y] + " ");
}
System.out.println("\n");
}
/**
* 冒泡排序
* @param arr
*/
public static void bubbleSort ( int[] arr){
for (int i = 0;i < arr.length-1;i++){
for (int x=0;x<arr.length-1;x++){
if (arr[x]>arr[x+1]){
int temp = arr[x];
arr[x] = arr[x+1];
arr[x+1] = temp;
}
}
System.out.println("第" + i + "次排序后");
printArray(arr);
}
}
}
本文来自博客园,作者:zhooke,转载请注明原文链接:https://www.cnblogs.com/zhooke/p/15399379.html