Write a method to sort the elements of a poset consisting of positive integers t
ID: 3601004 • Letter: W
Question
Write a method to sort the elements of a poset consisting of positive integers topologically with respect to the operation of divisibility. The input parameter of the method is an array containing the elements of the poset. Write a Java program that reads in a sequence of positive integers and displays the sorted list after sorting them topologically by using the above method. Your program should also display the minimal as well as the maximal elements of the poset. You must document your program nicely.
Sample run:
Enter the number of positive integers>
6
Please enter the numbers>
2 5 12 1 20 4
A topologically sorted listing> 1 5 2 4 20 12
Minimal elements: 1
Maximal elements: 20, 12
Explanation / Answer
This code has been run on ide platform and the output was successful. Incase of any error try giving positve number and enter the numbers in the same input , for example :6 2 5 12 1 20 4. Output is
A topologically sorted listing: 1 5 2 4 12 20
Minimal elements: 1
Maximal elements: 20
import java.util.Scanner;
public class main
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of positive integers ");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Please enter the numbers ");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("A topologically sorted listing: ");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.println(" Minimal elements:"+ a[0]);
System.out.println("Maximal elements:"+ a[n-1]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.