Ask user to give a size of array and then ask again if user wantsto enter the ar
ID: 3614489 • Letter: A
Question
Ask user to give a size of array and then ask again if user wantsto enter the array or if computer generates a random numbers. Ifuser wants to enter the numbers to fill the array, then ask numberand receive the value to fill the array. If not, use the randomnumber generator to fill the array and then display the currentarray.- And then use the bubble sort to sort the array and display theresult.
- Step-by-step example
- Let us take the array of numbers "5 1 4 2 8", and sort thearray from lowest number to greatest number using bubble sortalgorithm. In each step, elements written in bold are beingcompared.
- First Pass: ( 5 1 4 2 8 ) -> ( 1 5 4 2 8 ), Here, algorithmcompares the first two elements, and swaps them.
( 1 5 4 2 8 ) -> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ), Now, since these elements arealready in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) -> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does notknow if it is completed. The algorithm needs one whole pass withoutany swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.
Submission.
Explanation / Answer
public class Sort { public static void main(String[] args) { System.out.println("Enter size of array: "); String a1 = StdIn.readString(); int a2 = Integer.parseInt(a1); int[] num = new int [a2]; String b = ("Enter choice: 1 Enter the numbersin array 2 Let computer generates a random numbers "); System.out.println(b); String c1 = StdIn.readString(); int c2 = Integer.parseInt(c1); switch(c2) { case 1: { for(int i=0;iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.