How to generate random numbers in Java

Hey Folks,
I am up with another Java programming tutorial. In this tutorial, we will see how to generate random numbers in Java by taking an example of a bubble sort. Although bubble sort is not the best algorithm of sorting.

So let’s begin with our tutorial. Bubble sort has a time complexity of O(n*n). So it is not considered among good sorting algorithms. It is the least used sorting algorithm among competitive programmers.

Code to generate random numbers in Java

import java.util.Random;
import java.util.Arrays;
import java.util.Collections;
class BubbleSort
{
public static void main(String args[]) 
{ 

Integer[] arr; 
arr = new Integer[1000]; 
int n =1000; 
int temp,i,j,k;
for (i = 0; i < 1000; i++)
{
k=randomNumberInRange(999,9999);
arr[i]=k;
}
Arrays.sort(arr , Collections.reverseOrder());
//descending order
System.out.println("Sorted array: "); 
long startTime = System.currentTimeMillis();
for (i = 0; i < n - 1; i++)  
{ 
for (j = 0; j < n - i - 1; j++)  
{ 
  if (arr[j]>arr[j+1])  
    { 
    	temp=arr[j]; 
    	arr[j]=arr[j+1]; 
    	arr[j+1]=temp; 
    } 
}
} 
long endTime   = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime);

}
public static int randomNumberInRange(int min, int max) 
  {
        Random random = new Random();
        return random.nextInt((max - min) + 1) + min;
    }
}

We first create a class named same as our file name which is BubbleSort. Under it, we create our main class. We declare an integer array of size thousand elements. So to generate random numbers in a particular range we declare a user-defined function named randomNumberInRange.

Inside the user-defined function, we create an Object named random. This function just generated a random integer between the given range. Arrays.sort function sorts them in descending order as it is the best case of this sorting algorithm.

Now let’s talk about how bubble sort works. So it follows the most basic approach which one can think of. It picks up one element and checks it with each and every element if it is greater than the elementary element. So it swaps both the elements. It recursively repeats the same until the array is sorted.

I hope you understood the code well. You can ask if you have any doubts in the comments section below.

You may also read,

 

Leave a Reply

Your email address will not be published. Required fields are marked *