Write a single Java application (not required to be in a single source file) tha
ID: 3542300 • Letter: W
Question
Write a single Java application (not required to be in a single source file) that will prompt the user for an integer representing the size of an array of integers to be randomly generated. The program shall then:
1) Generate a randomized array of int values of the specified size in the range 0...max Java int.
2) Make a copy of the original array.
3) Display the first 50 ints in the array (to show that the values are not already ordered). 4) Sorts the copied array into non-descending order, using Selection Sort (see the online code and ppt slides).
5) Display the first 50 ints in the array (to show that the values are now in the specified order).
NOTE ; in Data Structures
Explanation / Answer
please rate - thanks
any question-ask
import java.util.*;
public class array
{
public static void main(String args[])
{int i,n;
Scanner in = new Scanner(System.in);
Random r=new Random();
System.out.print("How many numbers do you have? ");
n=in.nextInt();
int array[] = new int[n];
for(i=0;i<array.length;i++)
{array[i]=r.nextInt(Integer.MAX_VALUE);
}
int copy[]=new int[array.length];
for(i=0;i<array.length;i++)
{copy[i]=array[i];
}
print(array,"unsorted");
selectionSort(copy);
print(copy,"sorted");
}
public static void print(int array[],String message)
{int i,n;
if(array.length>50)
n=50;
else
n=array.length;
System.out.println("The first "+n+" numbers "+message);
for(i=0;i<n;i++)
{System.out.print(array[i]+" ");
if((i+1)%10==0)
System.out.println();
}
System.out.println();
}
public static void selectionSort(int[] a)
{int i,minIndex;
for(i=0;i<a.length-1;i++)
{minIndex = findMinimum(a,i);
if(minIndex!=i)
swap(a,i,minIndex);
}
}
public static int findMinimum(int[]a, int first)
{int i,minIndex = first;
for(i=first+1;i<a.length;i++)
if(a[i]<a[minIndex])
minIndex=i;
return minIndex;
}
public static void swap(int[] a, int x, int y)
{int temp = a[x];
a[x]=a[y];
a[y]=temp;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.