Java please.
Given a sequence of unsorted numbers, determine how badly out of order they are. Write a program that, for any given sequence of unique natural numbers, will compute the 'distance' between that original ordering and the same set of numbers sorted in ascending order. The distance should be computed by calculating how far displaced each number is in the original ordering from its correct location in the sorted list and summing those results. For instance, given the list 9 2 5 6 3, the target list would be 2 3 5 6 9. In this case, the 9 is four positions out of place, the 2 is one position out of place, the 5 and 6 are in the correct locations, and the 3 is three positions out of place. Therefore, the distance is 4 + 1 + 0 + 0 + 3 = 8. Keyboard input will consist of a single integer, m, indicating the number of elements in the sequence. Followed on the next line the m integers in the list. Lists will contain at most 20 elements, each of which will be less than 100. For each sequence in the input, display the distance between the given ordering and its sorted counterpart. Refer to the sample output below.
Sample Runs:
Enter the number of elements in the sequence: 5
Enter the 5 integers: 9 2 5 6 3
The distance is: 8
Enter the number of elements in the sequence: 3
Enter the 5 integers: 1 49 99
The distance is: 0
Code is Given below:
=======================
import java.util.Arrays;
import java.util.Scanner;
public class Distance {
public static void main(String[] args) {
//creating scanner object to get
input from user
Scanner scn=new
Scanner(System.in);
System.out.print("Enter the number
of elements in the sequence: ");
int n=scn.nextInt();
//creating array to hold sequence
and sorted numbers
int []numbers=new int[n];
int []sorted=new int[n];
System.out.print("Enter the "+n+"
integers: ");
for(int i=0;i<n;i++) {
numbers[i]=scn.nextInt();
sorted[i]=numbers[i];
}
//sorting the array
Arrays.sort(sorted);
//Initializing distance to 0
int distance=0;
for(int i=0;i<n;i++) {
for(int
j=0;i<n;j++) {
if(numbers[i]==sorted[j]) {//checking if numbers
are equal
distance=distance+Math.abs(j-i);//adding distance
break;
}
}
}
//printing result
System.out.println("The distance
is: "+distance);
}
}
Output:
==========
Code Snapshot:
==================
Get Answers For Free
Most questions answered within 1 hours.