Write a program that will test a name) method no sorting routine from.docx
1. Write a program that will test a name) method no sorting
routine from the Library l. Prompt the user to enter a number
and now fill the Array List with that many randomly generated
integer number ranging from 1 to 50 2. Print these numbers
from the ArrayList on the screen. 3. Call the SelectionSort0
method passing this AITayList full with those numbers. 4. Print
the resulting sorted ArrayList of numbers on the screen.
Solution
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
public class Sort {
/**
* main method to test the selectionSort static method
*/
public static void main(String args[]) {
// declare and initialize an array list
ArrayList<Integer> arraylist = new ArrayList<Integer>();
// create a Scanner object
Scanner in = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
2. System.out.print("Enter number: ");
int number = scanner.nextInt();
System.out.println("The number is: " + number);
// Generate random numbers between 1-50 given in number
variable and add in arrayList
for(int i=0;i<number;i++)
arraylist.add(new Random().nextInt(50)+1);
// print the original array list
System.out.println("Numbers from arraylist are:");
System.out.println(arraylist);
// selection sort it
SelectionSort(arraylist);
// print the sorted array list
System.out.println("Sorted array is:");
System.out.print(arraylist);
}
public static void SelectionSort(ArrayList<Integer> data) {
// just return if the array list is null
if (data == null)
return;
// just return if the array list is empty or only has a single
element
if (data.size() == 0 || data.size() == 1)
return;
// declare an int variable to hold value of index at which
3. the element
// has the smallest value
int smallestIndex;
// declare an int variable to hold the smallest value for each
iteration
// of the outer loop
int smallest;
// for each index in the array list
for (int curIndex = 0; curIndex < data.size(); curIndex++)
{
/* find the index at which the element has smallest value
*/
// initialize variables
smallest = data.get(curIndex);
smallestIndex = curIndex;
for (int i = curIndex + 1; i < data.size(); i++) {
if (smallest > data.get(i)) {
// update smallest
smallest = data.get(i);
smallestIndex = i;
}
}
/* swap the value */
// do nothing if the curIndex has the smallest value
if (smallestIndex == curIndex)
4. ;
// swap values otherwise
else {
int temp = data.get(curIndex);
data.set(curIndex, data.get(smallestIndex));
data.set(smallestIndex, temp);
}
}
}
}
/*output
Enter number:
13
The number is:
13
Numbers from arraylist
are:
[6, 44, 38, 41, 38, 29, 47, 41, 23, 39, 5, 43,
42]
Sorted array
is: