Write the Java source code necessary to build a solution for the problem below:
ID: 3568598 • Letter: W
Question
Write the Java source code necessary to build a solution for the problem below:
Your new cell phone has an almost infinite ability to store phone numbers. You decide to store them in a sorted array. Since you are the newly hired recruiter for Smart People's University, you must store all of your contacts in this array. You notice that the city from which you recruit stores the phone numbers by neighborhood. Storing them by neighborhood will allow you to only view the phone numbers of the students in the area that you are currently visiting. Re-sorting the numbers seems to take a rather long time. Last week you saw a program on the Discovery Channel about the many ways that computers can sort things, so you decide to try the newly learned "Bubble Sort" algorithm. But, you decide to try this method out before you implement it on your new smart phone. To do this, create an array of 5000 randomly generated seven digit integers. To ensure that you always get a 7 digit number, multiply the number returned by the random number generator by 9,000,000. Then, add 1,000,000 to this number (that way you will always have a number with seven digits). Use the Bubble sort algorithm to sort the elements of the array. Analyze the efficiency of the program in Big O Notation. Specify the best and worst case time needed to sort the elements using Bubble sort.
Explanation / Answer
package njsgd;
import java.util.Random;
public class Bubble {
public static void BubbleSort( int [ ] num )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ )
{
if ( num[ j ] < num[j+1] ) // change to > for ascending sort
{
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String []args)
{
Random r=new Random();
int []arr=new int[5000];
for(int i=0;i<5000;i++)
{
arr[i] = 1000000 + (int)(Math.random()*9000000);
}
BubbleSort(arr);
for(int k=0;k<5000;k++)
{
System.out.println(arr[k]);
}
}
}
Time Comlexity is for best case=worst case=average case= O(n^2)
Space complexity is O(1)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.