Question

I am working on the divide/conquer algorithm. I am having a trouble with a print for...

I am working on the divide/conquer algorithm. I am having a trouble with a print for output from reading the file. Here is my work. When you see I put the comment with TODO. that one I am struck with readfile. I wonder if you'd able to help me to fix the readfile to find a single number. Here is the input3.txt (1 12 13 24 35 46 57 58 69). after that, the output should be 0.

int mergeInversion(int arr[], int l, int m, int r) {

// Size of two arrays

int n1 = m - l + 1;

int n2 = r - m;

/* Create temp arrays */

int L[] = new int[n1];

int R[] = new int[n2];

/* Copy data to temp arrays */

for (int i = 0; i < n1; ++i)

L[i] = arr[l + i];

for (int j = 0; j < n2; ++j)

R[j] = arr[m + 1 + j];

// Counting Inversion

int count = 0;

for (int i = 0; i < n1; i++) {

for (int j = 0; j < n2; j++) {

if (L[i] > R[j]) // Condition to check inversion

{

count++;

}

}

}

return count;

}

// Divide Approach for Inversion

int CountInversion(int arr[], int l, int r) {

int countInv = 0;

if (l < r) {

// Find the middle point

int m = (l + r) / 2;

// Sort first and second halves

countInv = countInv + CountInversion(arr, l, m); // Recursively doing Inversion for first sub array

countInv = countInv + CountInversion(arr, m + 1, r); // Recursively doing Inversion for second sub array

// Merge the sorted halves

countInv = countInv + mergeInversion(arr, l, m, r); // Counting Inversion in from first to Second array

}

return countInv;

}

// Driver method

public static void main(String args[]) throws Exception {

CountingInversion ob = new CountingInversion();

// TODO need to constructor for read file

File readFile = new File("input3.txt");

try {

Scanner scanner = new Scanner(readFile);

while (scanner.hasNextLine()) {

String data = scanner.nextLine();

System.out.println(data);

}

scanner.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

// Enter Array Values Here.

int arr_rev_sor[] = { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

int val = ob.CountInversion(arr_rev_sor, 0, arr_rev_sor.length - 1);

System.out.println("\nTotal Number Of Inversion(Reverse Sorted): " + val);

int arr_sor[] = { 21, 59, 98, 23, 1, 5, 97 };

val = ob.CountInversion(arr_sor, 0, arr_sor.length - 1);

System.out.println("\nTotal Number Of Inversion(Sorted): " + val);

// printing the output

System.out.println(); // TODO need to print for a single number.

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

import java.io.*;
import java.util.Scanner;
class CountingInversion{
int mergeInversion(int arr[], int l, int m, int r) {
// Size of two arrays
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/* Copy data to temp arrays */
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
// Counting Inversion
int count = 0;
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (L[i] > R[j]) // Condition to check inversion
{
count++;
}
}
}
return count;
}
// Divide Approach for Inversion
int CountInversion(int arr[], int l, int r) {
int countInv = 0;
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
countInv = countInv + CountInversion(arr, l, m); // Recursively doing Inversion for first sub array
countInv = countInv + CountInversion(arr, m + 1, r); // Recursively doing Inversion for second sub array
// Merge the sorted halves
countInv = countInv + mergeInversion(arr, l, m, r); // Counting Inversion in from first to Second array
}
return countInv;
}
// Driver method
public static void main(String args[]) throws Exception {
CountingInversion ob = new CountingInversion();
// TODO need to constructor for read file
File readFile = new File("input3.txt");
//Declaring array to store values from file
int arr[]=new int[9];

try {
Scanner scanner = new Scanner(readFile);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
// Splitting the data based on space
// and store it in an string array
String[] ar = data.split(" ");
//Loop to store string elements as integer elements in array
for(int i = 0;i<ar.length;i++){
arr[i] = Integer.parseInt(ar[i]);

}
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Enter Array Values Here.
int arr_rev_sor[] = { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int val = ob.CountInversion(arr_rev_sor, 0, arr_rev_sor.length - 1);
System.out.println("\nTotal Number Of Inversion(Reverse Sorted): " + val);
int arr_sor[] = { 21, 59, 98, 23, 1, 5, 97 };
val = ob.CountInversion(arr_sor, 0, arr_sor.length - 1);
System.out.println("\nTotal Number Of Inversion(Sorted): " + val);
// Here we use the array which stores the elements in reading file
// printing the output
val = ob.CountInversion(arr, 0, arr.length - 1);
System.out.println("\nTotal Number Of Inversion: " + val); //Here ouptut is 0.

}
}

CODE SCREENSHOTS:

OUTPUT:

Here I highlighted the code in your program that used to read a file and print output.

Please Don't foget to UPVOTE my solution and Comment if you have any Doubts. I will definitely Answer.

Add a comment
Know the answer?
Add Answer to:
I am working on the divide/conquer algorithm. I am having a trouble with a print for...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • I have spent so much time on this and I am having trouble getting all the...

    I have spent so much time on this and I am having trouble getting all the methods to work together correctly to run the code right, and I am not sure what is wrong with it. /* You will recreate one or two versions of the logic game shown in the Algorithms movie and you will ask which one the user would like to play. Upon completion of the game, display who won and ask if they would like to...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I have a program that reads a file and then creates objects from the contents of...

    I have a program that reads a file and then creates objects from the contents of the file. How can I create a linked list of objects and use it with the package class instead of creating and using an array of objects? I am not allowed to use any arrays of objects or any java.util. lists in this program. Runner class: import java.util.Scanner; import java.io.*; class Runner { public static Package[] readFile() { try { File f = new...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • Java Im doing a binary search on an array and need to allow as many queries...

    Java Im doing a binary search on an array and need to allow as many queries as possible and cannot figure out how to. The output should read something like this. Enter a number. 3 3 is a prime number. Enter another number. 4 4 is not a prime number. Enter another number. 8 Current file not large enough for 8. Enter another number. -1 Bye. My code so far looks like this. public static void main(String[] args)    {...

  • How would I be able to get a Merge Sort to run in this code? MY...

    How would I be able to get a Merge Sort to run in this code? MY CODE: #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include <time.h> using namespace std; class mergersorter { private:    float array[1000] ;    int n = 1000;    int i=0; public:    void fillArray()    {        for(i=1;i<=n;i++)        {            array[i-1]= ( rand() % ( 1000) )+1;        }    }    void arrayout ()    {   ...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • the code needs to be modifed. require a output for the code Java Program to Implement...

    the code needs to be modifed. require a output for the code Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT