I'm having some problems trying to figure out how to insert an integer using a scanner into an ArrayList. I'm not that great (actually not even really good) at java but I'm just trying to figure some things out and any help would be great.
package mySort;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class MergeInsert {
private int limit = 100;
//private int size = 0;
private ArrayList<Integer> ArrayToSort;
public MergeInsert(int x) {
ArrayToSort = new ArrayList<Integer>(x);
}
public MergeInsert(Scanner integerScan){
int j = 0;
while(integerScan.hasNextInt()){
this.insert(integerScan.hasNextInt());
if (j % 10000 == 0){
long time = System.nanoTime();
System.out.println(j + "," + time);
}
}
}
public void insert(int x){
for(int i=0; i<ArrayToSort.size(); i++){
ArrayToSort(size++) = x;
}
}
// public MergeInsert(int v){
// int val = v;
// }
// public void insertFile(){
// try {
// Scanner integerScan = new Scanner(new FileInputStream(""));
// while(integerScan.hasNextInt()){
// new MergeInsert(integerScan.nextInt());
// }
// }
// catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
public void sort(){
}
public void mergeSort(ArrayList<Integer> in, int low,int high){
int n = in.size();
int mid = (high+low)/2;
if (n<2){ //already sorted
return;
}
if ((high - low) < limit){
insertionSort(in);
}
ArrayList<Integer> in1 = new ArrayList<Integer>(); //helper
ArrayList<Integer> in2 = new ArrayList<Integer>(); //helper
int i=0;
while (i < n/2){ //moves the first half to the helper
in1.add(in.remove(0));
i++;
}
while (!in.isEmpty()) //moves the second half to the helper
in2.add(in.remove(0));
mergeSort(in1, low, mid); //breaks it down some more like mergesort should
mergeSort(in2, mid+1, high); //does it again
merge(in1,in2,in); //trying to build it up again
}
public void merge(ArrayList<Integer> in, ArrayList<Integer> in1, ArrayList<Integer> in2){
while (!in1.isEmpty() || !in2.isEmpty()) //as long as both helpers still have elements
if ((in1.get(0).compareTo(in2.get(0)) <= 0)) //comparison to rebuild
in.add(in1.remove(0)); //building it back up
else
in.add(in2.remove(0)); //still building
while(!in1.isEmpty()) //as long as the first helper isn't empty keep building
in.add(in1.remove(0));
while(!in2.isEmpty()) //as long as the second helper isn't empty keep building
in.add(in2.remove(0));
}
public ArrayList<Integer> insertionSort(ArrayList<Integer> in){
int index = 1;
while (index<in.size()){
insertSorted((int)(in.get(index)),in,index);
index = index +1;
}
return in;
}
public ArrayList<Integer> insertSorted(Integer s, ArrayList<Integer> in, int index){
int loc = index-1;
while((loc>=0) || s.compareTo(in.get(loc)) <= 0){
in.set(loc + 1, in.get(loc));
loc = loc -1;
}
in.set(loc+1, s);
return in;
}
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
Scanner integerScan = new Scanner(new FileInputStream("src/myRandomNumbers.txt"));
MergeInsert myObject = new MergeInsert(integerScan);
myObject.sort();
}
}
It's not completely finished but the idea behind all of this is to try and improve on MergeSort. Basically once the elements get broken down to a certain point cut to InsertionSort because it is usually better on really small (really small being relative) sets of data.
public void insert(int x){
ArrayToSort.add(x); // add it to the end
}
The reason is... even if you go
ArrayToSort = new ArrayList<Integer>(100000);
It still has a size of 0. It just has a CAPACITY of 100000.
Use add to insert objects into the list.
Also, the way your code is structured now, you will get a NullPointerException when you attempt to invoke add because the constructor you invoke never initializes the list.
Given the quality of your code, I highly recommend reading Learning the Java Language.
Related
I was asked to program a method that receives a scanner, and returns a sorted array of words which contain only letters, with no repetitions (and no bigger in length than 3000). Then, I was asked to program a method that checks whether a certain given string is contained in a given vocabulary. I used a simple binary search method.
This is what I've done:
public static String[] scanVocabulary(Scanner scanner){
String[] array= new String[3000];
int i=0;
String word;
while (scanner.hasNext() && i<3000) {
word=scanner.next();
if (word.matches("[a-zA-Z]+")){
array[i]=word.toLowerCase();
i++;
}
}int size=0;
while (size<3000 && array[size]!=null ) {
size++;
}
String[] words=Arrays.copyOf(array, size);
if (words.length==0 || words.length==1) {
return words;
}
else {
Arrays.sort(words);
int end= removeDuplicatesSortedArr(words);
return Arrays.copyOf(words, end);
}
}
private static int removeDuplicatesSortedArr(String[] array) { //must be a sorted array. returns size of the new array
int n= array.length;
int j=0;
for (int i=0; i<n-1; i++) {
if (!array[i].equals(array[i+1])) {
array[j++]=array[i];
}
}
array[j++]=array[n-1];
return j;
}
public static boolean isInVocabulary(String[] vocabulary, String word){
//binary search
int n=vocabulary.length;
int left= 0;
int right=n-1;
while (left<=right) {
int mid=(left+right)/2;
if (vocabulary[mid].equals(word)){
return true;
}
else if (vocabulary[mid].compareTo(word)>0) {
right=mid-1;
}else {
right=mid+1;
}
}
return false;
}
while trying the following code:
public static void main(String[] args) {
String vocabularyText = "I look at the floor and I see it needs sweeping while my guitar gently weeps";
Scanner vocabularyScanner = new Scanner(vocabularyText);
String[] vocabulary = scanVocabulary(vocabularyScanner);
System.out.println(Arrays.toString(vocabulary));
boolean t=isInVocabulary(vocabulary, "while");
System.out.println(t);
System.out.println("123");
}
I get nothing but-
[and, at, floor, gently, guitar, i, it, look, my, needs, see, sweeping, the, weeps, while]
nothing else is printed out nor returned. Both functions seem to be working fine separately, so I don't get what I'm doing wrong.
I would be very happy to hear your thoughts, thanks in advance :)
This has nothing to do with the console. Your isInVocabulary method is entering an infinite loop in this block:
if (!isInVocabulary(vocabulary, "while")) {
System.out.println("Error");
}
If you were to debug through isInVocabulary, you would see that after a few iterations of the while loop,
left = 0;
right = 2;
mid = 1;
if (vocabulary[mid].equals(word)){
// it doesn't
} else if (vocabulary[mid].compareTo("while") > 0) {
// it doesn't
} else {
right = mid + 1;
// this is the same as saying right = 1 + 1, i.e. 2
}
So you'll loop forever.
I have to create a java program with two classes and the challenge is =
"Enter in 10 numbers. Calculate the average and display all numbers greater than the average."
I am fairly new to java and I have no idea on what I am doing and how to send array values from one class to another.
import BreezySwing.KeyboardReader;
import javax.swing.*;
public class Average {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
System.out.print('\u000C');
AverageTest at = new AverageTest();
int numberArray[];
int i;
numberArray = new int[10];
for (i = 0; i < 10; i++) {
numberArray[i] = reader.readInt("Enter a number: ");
at.setnumber(numberArray);
}
}
}
import javax.swing.*;
import BreezySwing.*;
public class AverageTest
{
private int number[];
private int a;
public void setnumber(int number)
{
number = numberArray;
}
}
import java.util.Scanner;
public class AverageTest {
public static void main(String[] args) {
int[] array = new int[10];
// Try with resources, automatically closes the reader once the work is done
// Read 10 integers from the standard input
try (Scanner reader = new Scanner(System.in);) {
for (int i = 0; i < 2; i++) {
System.out.println("Enter a number: ");
array[i] = reader.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
// we have an array with 10 numbers, now create an average object by passing
// this array to the Average class constructor
Average averageObj = new Average(array);
// Compute the average
float average = averageObj.average();
System.out.println("Average: " + average);
System.out.println("Numbers greater than average: ");
// Print out the numbers which are greater than or equal to the average
for (int i = 0; i < array.length; i++) {
if (array[i] >= average) {
System.out.println(array[i]);
}
}
}
}
class Average {
private int[] array;
public Average(int[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array cannot be null or empty");
}
this.array = array;
}
public int[] getArray() {
return array;
}
/**
* Computes the average of the given array and returns it.
*/
public float average() {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return (float) sum/array.length;
}
}
there are 3 steps about this issue:
1.Enter in 10 numbers.
2.Calculate the average.
3.display all numbers greater than the average.
you have done the step 1,that's great.
and I can see that you are trying to do the step 2.
here's the suggestion of your issue:
if you want to send array values from A class to B,you just need to invoke the method of B in the A correctly.
I think I know what you are trying to do.
the problem of your code that you can't send array values from one class to another is because the method's parameter type is not matching.
the method public void setnumber(int number),the parameter is an int type,and you try to refer it to an int array,this's wrong.
first, you need to change the method's definition to public void setnumber(int[] numberarray),and try to figure out why we have to write like this.
then finish the step 2.
Hope it'll help.
I have applied the KNN algorithm for classifying handwritten digits. the digits are in vector format initially 8*8, and stretched to form a vector 1*64..
As it stands my code applies the kNN algorithm but only using k = 1. I'm not entirely sure how to alter the value k after attempting a couple of things I kept getting thrown errors. If anyone could help push me in the right direction it would be really appreciated. The training dataset can be found here and the validation set here.
ImageMatrix.java
import java.util.*;
public class ImageMatrix {
private int[] data;
private int classCode;
private int curData;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64; //maximum array length of 64
this.data = data;
this.classCode = classCode;
}
public String toString() {
return "Class Code: " + classCode + " Data :" + Arrays.toString(data) + "\n"; //outputs readable
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
public int getCurData() {
return curData;
}
}
ImageMatrixDB.java
import java.util.*;
import java.io.*;
import java.util.ArrayList;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
private List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public ImageMatrixDB load(String f) throws IOException {
try (
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
String line = null;
while((line = br.readLine()) != null) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
ImageMatrix matrix = new ImageMatrix(data, classCode); // Classcode->100% when 0 -> 0% when 1 - 9..
list.add(matrix);
}
}
return this;
}
public void printResults(){ //output results
for(ImageMatrix matrix: list){
System.out.println(matrix);
}
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
/// kNN implementation ///
public static int distance(int[] a, int[] b) {
int sum = 0;
for(int i = 0; i < a.length; i++) {
sum += (a[i] - b[i]) * (a[i] - b[i]);
}
return (int)Math.sqrt(sum);
}
public static int classify(ImageMatrixDB trainingSet, int[] curData) {
int label = 0, bestDistance = Integer.MAX_VALUE;
for(ImageMatrix matrix: trainingSet) {
int dist = distance(matrix.getData(), curData);
if(dist < bestDistance) {
bestDistance = dist;
label = matrix.getClassCode();
}
}
return label;
}
public int size() {
return list.size(); //returns size of the list
}
public static void main(String[] argv) throws IOException {
ImageMatrixDB trainingSet = new ImageMatrixDB();
ImageMatrixDB validationSet = new ImageMatrixDB();
trainingSet.load("cw2DataSet1.csv");
validationSet.load("cw2DataSet2.csv");
int numCorrect = 0;
for(ImageMatrix matrix:validationSet) {
if(classify(trainingSet, matrix.getData()) == matrix.getClassCode()) numCorrect++;
} //285 correct
System.out.println("Accuracy: " + (double)numCorrect / validationSet.size() * 100 + "%");
System.out.println();
}
In the for loop of classify you are trying to find the training example that is closest to a test point. You need to switch that with a code that finds K of the training points that is the closest to the test data. Then you should call getClassCode for each of those K points and find the majority(i.e. the most frequent) of the class codes among them. classify will then return the major class code you found.
You may break the ties (i.e. having 2+ most frequent class codes assigned to equal number of training data) in any way that suits your need.
I am really inexperienced in Java, but just by looking around the language reference, I came up with the implementation below.
public static int classify(ImageMatrixDB trainingSet, int[] curData, int k) {
int label = 0, bestDistance = Integer.MAX_VALUE;
int[][] distances = new int[trainingSet.size()][2];
int i=0;
// Place distances in an array to be sorted
for(ImageMatrix matrix: trainingSet) {
distances[i][0] = distance(matrix.getData(), curData);
distances[i][1] = matrix.getClassCode();
i++;
}
Arrays.sort(distances, (int[] lhs, int[] rhs) -> lhs[0]-rhs[0]);
// Find frequencies of each class code
i = 0;
Map<Integer,Integer> majorityMap;
majorityMap = new HashMap<Integer,Integer>();
while(i < k) {
if( majorityMap.containsKey( distances[i][1] ) ) {
int currentValue = majorityMap.get(distances[i][1]);
majorityMap.put(distances[i][1], currentValue + 1);
}
else {
majorityMap.put(distances[i][1], 1);
}
++i;
}
// Find the class code with the highest frequency
int maxVal = -1;
for (Entry<Integer, Integer> entry: majorityMap.entrySet()) {
int entryVal = entry.getValue();
if(entryVal > maxVal) {
maxVal = entryVal;
label = entry.getKey();
}
}
return label;
}
All you need to do is adding K as a parameter. Keep in mind, however, that the code above does not handle ties in a particular way.
I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable
adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132
And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1
The problems with my code are as follows:
It doesn't sort based off the index
It gives me an error at runtime with the code: Arrays.sort(c);
Please help with suggestions
Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Prog4 {
static Scanner input;
static File filename;
/**
* This function displays the menu for the user to choose an option from
*/
public void menu() {
System.out.println("Option 1: Sort by VENDOR: ");
System.out.println("Option 2: Sort decreasing number by MMAX: ");
System.out.println("Option 3: Sort decreasing number by CACH: ");
System.out.println("Option 4: Sort decreasing number by PRP: ");
System.out.println("Option 5: Quit program");
}
/**
* Constructor to handle the cases in the menu options
* #throws FileNotFoundException
* #throws IOException
*/
public Prog4() throws FileNotFoundException {
//Accepts user input
Scanner in = new Scanner(System.in);
//calls the menu method
menu();
//Initializes the run variable making the program loop until the user terminates the program
Boolean run = true;
//While loop
while (run) {
switch (in.nextInt()) {
case 1:
System.out.println("Option 1 selected");
System.out.println("Sorted by vendor:");
filename = new File("machine.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new Array of String type
String array [] = new String[10];
//while it has next ..
while (input.hasNext()) {
//Initialize variable
int i = 0;
//store each word read in array and use variable to move across array array[i] = input.next();
//print
System.out.println(array[i]);
//so we increment so we can store in the next array index
i++;
}
case 2:
System.out.println("Press any key to continue");
Scanner input2 = new Scanner(System.in);
String x = input2.nextLine();
if (x.equals(0)) continue;
System.out.println("Option 2 selected") ;
Computer[] c = new Computer[10];
filename = new File("machine.txt");
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Arrays.sort(c);
while (input.hasNextLine()) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
}
}
/**
* Main method
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
//Calls the constructor
new Prog4();
//static Scanner input;
}
public static void quickSort(int arr[], int left, int right) {
if (left < right) {
int q = partition(arr, left, right);
quickSort(arr, left, q);
quickSort(arr, q+1, right);
}
}
private static int partition(int arr[], int left, int right) {
int x = arr[left];
int i = left - 1;
int j = right + 1;
while (true) {
i++;
while (i < right && arr[i] < x)
i++;
j--;
while (j > left && arr[j] > x)
j--;
if (i < j)
swap(arr, i, j);
else
return j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Comparator class:
import java.util.Comparator;
class Computer implements Comparable<Computer> {
private String vendor;
private int mmax;
private int cach;
private int php;
public Computer(int value) {
this.mmax = value;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getMmax() {
return mmax;
}
public void setMmax(int mmax) {
this.mmax = mmax;
}
public int getCach() {
return cach;
}
public void setCach(int cach) {
this.cach = cach;
}
public int getPhp() {
return php;
}
public void setPhp(int php){
this.php = php;
}
#Override
public int compareTo(Computer m) {
if (mmax < m.mmax) {
return -1;
}
if (mmax > m.mmax) {
return 1;
}
// only sort by height if age is equal
if (cach > m.cach) {
return -1;
}
if (cach < m.cach) {
return 1;
}
if (php > m.php) {
return -1;
}
if (php < m.php) {
return 1;
}
return 0;
}
public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
#Override
public int compare(Computer p1, Computer p2) {
return p2.getMmax() - p1.getMmax();
}
};
}
The biggest problem is that the Computer classes do not get instantiated for each line that gets read.
As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.
I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.
Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
Create a blank ArrayList to store the Computer objects.
Iterate through the file and readLine
Call the Computer constructor using the String representing each line in the file within the while loop
Add the new Computer object to the computers ArrayList
Write 5 different comparators.
Based on user input, instantiate the correct comparator and pass it to the sort method
Print the sorted array
If you still face a problem, mention the specific point at which you like more clarity..
I'm taking an online class on Algorithms and trying to implement a mergesort implementation of finding the number of inversions in a list of numbers. But, I cant figure what Im doing wrong with my implementation as the number of inversions returned is significantly lower than the number I get while doing a brute force approach. Ive placed my implementation of the mergesort approach below
/**
*
*/
package com.JavaReference;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String args[]){
int count=0;
Integer n[];
int i=0;
try{
n=OpenFile();
int num[] = new int[n.length];
for (i=0;i<n.length;i++){
num[i]=n[i].intValue();
// System.out.println( "Num"+num[i]);
}
count=countInversions(num);
}
catch(IOException e){
e.printStackTrace();
}
System.out.println(" The number of inversions"+count);
}
public static Integer[] OpenFile()throws IOException{
FileReader fr=new FileReader("C:/IntegerArray.txt");// to put in file name.
BufferedReader textR= new BufferedReader(fr);
int nLines=readLines();
System.out.println("Number of lines"+nLines);
Integer[] nData=new Integer[nLines];
for (int i=0; i < nLines; i++) {
nData[ i ] = Integer.parseInt((textR.readLine()));
}
textR.close();
return nData;
}
public static int readLines() throws IOException{
FileReader fr=new FileReader("C:/IntegerArray.txt");
BufferedReader br=new BufferedReader(fr);
int numLines=0;
//String aLine;
while(br.readLine()!=null){
numLines++;
}
System.out.println("Number of lines readLines"+numLines);
return numLines;
}
public static int countInversions(int num[]){
int countLeft,countRight,countMerge;
int mid=num.length/2,k;
if (num.length<=1){
return 0;// Number of inversions will be zero for an array of this size.
}
int left[]=new int[mid];
int right[]=new int [num.length-mid];
for (k=0;k<mid;k++){
left[k]=num[k];
}
for (k=0;k<mid;k++){
right[k]=num[mid+k];
}
countLeft=countInversions(left);
countRight=countInversions(right);
int[] result=new int[num.length];
countMerge=mergeAndCount(left,right,result);
/*
* Assign it back to original array.
*/
for (k=0;k<num.length;k++){
num[k]=result[k];
}
return(countLeft+countRight+countMerge);
}
private static int mergeAndCount(int left[],int right[],int result[]){
int count=0;
int a=0,b=0,i,k=0;
while((a<left.length)&&(b<right.length)){
if(left[a]<right[b]){
result[k]=left[a++];// No inversions in this case.
}
else{// There are inversions.
result[k]=right[b++];
count+=left.length-a;
}
k++;
// When we finish iterating through a.
if(a==left.length){
for (i=b;i<right.length;i++){
result[k++]=right[b];
}
}
else{
for (i=a;i<left.length;i++){
}
}
}
return count;
}
}
I'm a beginner in Java and Algorithms so any insightful suggestions would be great!
I found two bugs:
In countInversions(), when num is split into left and right you assume right has m elements. When num.length is odd, however, it will be m + 1 elements. The solution is to use right.length instead of m.
In mergeAndCount(), handling of the bit where one subarray is empty and the other one still has some elements is not done correctly.
Side note:
There is absolutely no reason to use Integer in your program, except for the Integer.parseInt() method (which, by the way, returns an int).
Corrected code:
/**
*
*/
package com.JavaReference;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String args[]){
int count=0;
Integer n[];
int i=0;
try{
n=OpenFile();
int num[] = new int[n.length];
for (i=0;i<n.length;i++){
num[i]=n[i].intValue();
// System.out.println( "Num"+num[i]);
}
count=countInversions(num);
}
catch(IOException e){
e.printStackTrace();
}
System.out.println(" The number of inversions"+count);
}
public static Integer[] OpenFile()throws IOException{
FileReader fr=new FileReader("C:/IntegerArray.txt");// to put in file name.
BufferedReader textR= new BufferedReader(fr);
int nLines=readLines();
System.out.println("Number of lines"+nLines);
Integer[] nData=new Integer[nLines];
for (int i=0; i < nLines; i++) {
nData[ i ] = Integer.parseInt((textR.readLine()));
}
textR.close();
return nData;
}
public static int readLines() throws IOException{
FileReader fr=new FileReader("C:/IntegerArray.txt");
BufferedReader br=new BufferedReader(fr);
int numLines=0;
//String aLine;
while(br.readLine()!=null){
numLines++;
}
System.out.println("Number of lines readLines"+numLines);
return numLines;
}
public static int countInversions(int num[]){
int countLeft,countRight,countMerge;
int mid=num.length/2,k;
if (num.length<=1){
return 0;// Number of inversions will be zero for an array of this size.
}
int left[]=new int[mid];
int right[]=new int [num.length-mid];
for (k=0;k<mid;k++){
left[k]=num[k];
}
// BUG 1: you can't assume right.length == m
for (k=0;k<right.length;k++){
right[k]=num[mid+k];
}
countLeft=countInversions(left);
countRight=countInversions(right);
int[] result=new int[num.length];
countMerge=mergeAndCount(left,right,result);
/*
* Assign it back to original array.
*/
for (k=0;k<num.length;k++){
num[k]=result[k];
}
return(countLeft+countRight+countMerge);
}
private static int mergeAndCount(int left[],int right[],int result[]){
int count=0;
int a=0,b=0,i,k=0;
while((a<left.length)&&(b<right.length)){
if(left[a]<right[b]){
result[k]=left[a++];// No inversions in this case.
}
else{// There are inversions.
result[k]=right[b++];
count+=left.length-a;
}
k++;
}
// BUG 2: Merging of leftovers should be done like this
while (a < left.length)
{
result[k++] = left[a++];
}
while (b < right.length)
{
result[k++] = right[b++];
}
return count;
}
}
The way I see it, counting the number of inversions in an array is finding a way to sort the array in an ascending order. Following that thought, here is my solution:
int countInversionArray(int[] A) {
if(A.length<=1) return 0;
int solution = 0;
for(int i=1;i<A.length;i++){
int j = i;
while(j+2<A.length && A[j] > A[j+1]){
invert2(j,j+1,A);
solution++;
j++;
}
j=i;
while(j>0 && A[j] < A[j-1]){
invert2(j,j-1,A);
solution++;
j--;
}
}
return solution;
}
private void invert2(int index1, int index2, int[] A){
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
I found a rigth solution in Robert Sedgewick book "Algorithms on java language"
Read here about merge
See java code for counting of inversion
You can try this In-Place Mergesort implemention on java. But minimum 1 temporary data container is needed (ArrayList in this case). Also counts inversions.
///
Sorter.java
public interface Sorter {
public void sort(Object[] data);
public void sort(Object[] data, int startIndex, int len);
}
MergeSorter implementation class (others like QuickSorter, BubbleSorter or InsertionSorter may be implemented on Sorter interface)
MergeSorter.java
import java.util.List;
import java.util.ArrayList;
public class MergeSorter implements Sorter {
private List<Comparable> dataList;
int num_inversion;
public MergeSorter() {
dataList = new ArrayList<Comparable> (500);
num_inversion = 0;
}
public void sort(Object[] data) {
sort(data, 0, data.length);
}
public int counting() {
return num_inversion;
}
public void sort(Object[] data, int start, int len) {
if (len <= 1) return;
else {
int midlen = len / 2;
sort(data, start, midlen);
sort(data, midlen + start, len - midlen);
merge(data, start, midlen, midlen + start, len - midlen);
}
}
private void merge(Object[] data, int start1, int len1, int start2, int len2) {
dataList.clear();
int len = len1 + len2;
// X is left array pointer
// Y is right array pointer
int x = start1, y = start2;
int end1 = len1 + start1 - 1;
int end2 = len2 + start2 - 1;
while (x <= end1 && y <= end2) {
Comparable obj1 = (Comparable) data[x];
Comparable obj2 = (Comparable) data[y];
Comparable<?> smallobject = null;
if (obj1.compareTo(obj2) < 0) {
smallobject = obj1;
x++;
}
else {
smallobject = obj2;
y++;
num_inversion += (end1 - x + 1);
}
dataList.add(smallobject);
}
while (x <= end1) {
dataList.add((Comparable)data[x++]);
}
while (y <= end2) {
dataList.add((Comparable)data[y++]);
}
for (int n = start1, i = 0; n <= end2; n++, i++) {
data[n] = dataList.get(i);
}
}
}
For testing, create a driver class and type the main method
public static void main(String[] args) {
Object[] data = ...............
Sorter sorter = new MergeSorter();
sorter.sort(data)
for (Object x : data) {
System.out.println(x);
}
System.out.println("Counting invertion: " + ((MergeSorter)sorter).counting());
}