Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7697083
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T21:55:43+00:00 2026-05-31T21:55:43+00:00

I wrote an implementation of inversion-counting. This is an assignment being carried out in

  • 0

I wrote an implementation of inversion-counting. This is an assignment being carried out in an online course. But the input i get isn’t correct and according to what I have the program has a correct syntax. I dont just know were I went wrong
The program below is my implementation

import java.io.*;

class CountInversions {
    //Create an array of length 1 and keep expanding as data comes in

    private int elements[];
    private int checker = 0;

    public CountInversions() {
        elements = new int[1];
        checker = 0;
    }

    private boolean isFull() {
        return checker == elements.length;
    }

    public int[] getElements() {
        return elements;
    }

    public void push(int value) {
        if (isFull()) {
            int newElements[] = new int[elements.length * 2];
            System.arraycopy(elements, 0, newElements, 0, elements.length);
            elements = newElements;
        }
        elements[checker++] = value;
    }

    public void readInputElements() throws IOException {
        //Read input from file and until the very last input
        try {
            File f = new File("IntegerArray.txt");
            FileReader fReader = new FileReader(f);
            BufferedReader br = new BufferedReader(fReader);
            String stringln;
            while ((stringln = br.readLine()) != null) {
                push(Integer.parseInt(stringln));
            }
            System.out.println(elements.length);
            fReader.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        } finally {
//            in.close
        }
    }  
        //Perform the count inversion algorithm
    public int countInversion(int array[],int length){
        int x,y,z;
        int mid = array.length/2 ;
        int k;
        if (length == 1){
            return 0;
        }else{
            //count Leftinversion and count Rightinversion respectively
            int left[] = new int[mid];
            int right[] = new int[array.length - mid];

            for(k = 0; k < left.length;k++){
                left[k] = array[k];
            }

            for(k = 0 ;k < right.length;k++){
                right[k] = array[mid + k];
            }
            x = countInversion(left, left.length);
            y = countInversion(right, right.length);
            int result[] = new int[array.length];
            z = mergeAndCount(left,right,result);

            //count splitInversion
            return x + y + z;
        }   
    }

    private int mergeAndCount(int[] left, int[] right, int[] result) {
        int count = 0;
        int i = 0, j = 0, k = 0;
        int m = left.length, n = right.length;
        while(i < m && j < n){
            if(left[i] < right[j]){
                result[k++] = left[i++];
            }else{
                result[k++] = right[j++];
                count += left.length - i;
            }
        }
        if(i < m){
            for (int p = i ;p < m ;p++){
                result[k++] = left[p];
            }
        }
        if(j < n){
            for (int p = j ;p < n ;p++){
                result[k++] = right[p];
            }
        }
        return count;
    }
}
class MainApp{
    public static void main(String args[]){
        int count = 0;
        CountInversions cIn = new CountInversions();
        try {
            cIn.readInputElements();
            count = cIn.countInversion(cIn.getElements(),cIn.getElements().length);
            System.out.println("Number of Inversios: " + count);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T21:55:44+00:00Added an answer on May 31, 2026 at 9:55 pm

    Your code works if the array length is a power of 2 (actually, I’m not sure whether if does, see second point below).

    When reading the input, you double the array size when it’s full, but you never resize it to the number of actually read items, which is stored in checker. So your array length is a power of 2, and if the number of ints read from the file is not a power of 2, you have a too long array with some trailing 0 elements corresponding to the places allocated but not filled from the file. Since you call countInversions with the length of the array and not with the number of read items, these 0s are sorted too, yielding some spurious inversions.

    After reading the input, allocate a new array

    int[] copy = new int[checker];
    for(int i = 0; i < checker; ++i) {
        copy[i] = elements[i];
    }
    elements = copy;
    

    copy the elements, and discard the old array with the wrong capacity.

    Another problem in your algorithm is that you never change the original array because you allocate a new array for the merge result,

    int result[] = new int[array.length];
    z = mergeAndCount(left,right,result);
    

    so you are merging unsorted arrays, which may also skew the inversion count. Since you copied the halves of the input array to new arrays for the recursive calls, you can without problem put the merge result in the passed-in array, so replace the above two lines with

    z = mergeAndCount(left,right,array);
    

    to get a method that actually sorts the array and counts the inversions.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote this tiny little wrapper around order , but I fear my implementation
I wrote this implementation of the Sieve of Eratosthenes in c++, but whenever the
I wrote an implementation of the Mandelbrot set in Java using a JComponent but
I wrote a linked list implementation for my java class earlier this year. This
I wrote a WCF service, but the data stored in the Service implementation doesn't
I wrote a simple map implementation for some task. Then, out of curiosity, I
I wrote an implementation of vector, which compiles but is not working properly according
I wrote an exam paper today, for a university course concerned with the implementation
Out of curiosity, I wrote an own simple implementation of Set for a special
I wrote an implementation for a priority queue I needed, and now I would

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.