Sorting Algorithm (a) - generating a random array

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/A1344714150/article/details/88635720

Because bloggers recently wanted to interview, you need to re-review under algorithms and data structures, where a simple gathering information.

Objective: to generate and return an integer contains n elements, values ranging left ~ right array;

Here a SortUtil as a custom ordered tools

Implementation process: incoming parameters n, Left, Right. To declare an array of size n is an integer array, the array element assigned to the loop (int) (Math.random () * (Right-Left) + Left), wherein Math.Random () * (Right-Left ) can to the value 0 generated by the Right-Left, on this basis with Left value, and finally turn strong, so that to the Left ~ Right value is a random value range;

Code:

//排序工具类(默认从小到大排序)
public class SortUtil {

	//返回元素个数为n,数值范围是Left~Right(不包含Right)的随机数组
	public static int[] getRandomArrayData(int n,int Left,int Right){
		int[] array = new int[n];
		for(int i=0;i<n;i++){
			array[i] = (int) (Math.random()*(Right-Left)+Left);			
		}
		
		return array;
	}

}

Client class is generated for printing the array:

import java.util.Scanner;

public class Client {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int left = input.nextInt();
		int right = input.nextInt();
		int[] array = SortUtil.getRandomArrayData(n, left, right);
		System.out.println("打印生成的数组:");
		print(array);
	}
	
	public static void print(int[] array){
		for(int i=0;i<array.length;i++){
			System.out.print(array[i]+" ");
		}
		System.out.println();
	}
	
}

Generating an array size of 10, an array of numerical range is 5 to 16, the output of the array:

Guess you like

Origin blog.csdn.net/A1344714150/article/details/88635720