How to sort a CSV file with merge sort JAVA


Joined
May 6, 2021
Messages
4
Reaction score
0
0
I have a task in which im given a CSV file which is like Name,Marks,Time next line Abe,24,23.6 etc with Strings and ints and i need to sort the Names based on Marks with merge sort and print them in another txt file.I have tried many ways but i think that it need to be done using an Arraylist with objects that as i read the file will be made and each will have a String and an Int,however i cant find the way to merge sort them later when needed.
Here is where i am now with all the info i found by other guys too The main class
'''

Java:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class Sort
{
public static void main(String[] args)throws IOException
    {
//Creating BufferedReader object to read the input text file
        
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\user\\Desktop\\ale.us.txt"));
        
//Creating ArrayList to hold Student objects
        
ArrayList<Metoxh> studentRecords = new ArrayList<Metoxh>();
        
//Reading Student records one by one
        
        String currentLine = reader.readLine();
try {
while (currentLine != null)
        {
String[] studentDetail = currentLine.split("");
            
String name = studentDetail[0];
            
int marks = Integer.valueOf(studentDetail[1]);
        
//Creating Student object for every student record and adding it to ArrayList
            
studentRecords.add(new Metoxh(name, marks));
            
            currentLine = reader.readLine();
        }
}catch(NumberFormatException e) {}
//Sorting ArrayList studentRecords based on marks
      
Collections.sort(studentRecords, new marksCompare());
        
//Creating BufferedWriter object to write into output text file
        
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\user\\Desktop\\skr.txt"));
        
//Writing every studentRecords into output text file
        
for (Metoxh student : studentRecords)
        {
            writer.write(student.name);
            
writer.write(" "+student.marks);
            
            writer.newLine();
        }
        
//Closing the resources
        
        reader.close();
        
        writer.close();
    }

    }


''' and 2 classes Metoxh and marksCompare which will be used to pass arguments to the objects of every line and pass them into they Arraylist(with Metoxh items). '''
Java:
public class Metoxh {

String name;
    
int marks;
    
public Metoxh(String name, int marks)
    {
this.name = name;
        
this.marks = marks;
    }

}

import java.util.Comparator;

class nameCompare implements Comparator<Metoxh>
    {
@Override
public int compare(Metoxh s1, Metoxh s2)
        {
return s1.name.compareTo(s2.name);
        }
}

Any help is much much appreciated
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
28
Reaction score
6
The easiest way to compare two primitive ints would be:

Java:
Integer.compare(a.marks, b.marks);

So, just copy the nameCompare class to marksCompare and update the return line. The only problem I see is the split:

Java:
String[] studentDetail = currentLine.split("");

This will split a line on every character, so studenDetail[1] will be the second character, not the second field. Just switch it to:

Java:
String[] studentDetail = currentLine.split(",");
 
Joined
May 6, 2021
Messages
4
Reaction score
0
Yea but it need to compare them with merge sort algorithm which i cant make for objects in this list,thanks a lot tho
 
Joined
Mar 3, 2021
Messages
28
Reaction score
6
Yeah, Java likely uses a Tim sort. But any sorting algorithm can be used on any object class, with the right comparisons. Sounds like the assignment is to implement the actual merge sort. I'd find a good pseudo-code version and work from there. You can pretty easily grab source code for ones for integer lists and modify it for your objects, but it might be quicker to do it from scratch. Whichever way you choose, if you run into problems, come back and post some more code.
 
Joined
May 6, 2021
Messages
4
Reaction score
0
Ive been trying to solve this so much but im just not good enough in this language, but as it seems i need in my nameCompare class to compare the marks values(int) without changing the name with merge sort and return the correct values somehow, thanks tho again
 
Joined
Mar 3, 2021
Messages
28
Reaction score
6
Do you have the merge sort written yet? Write a generic merge sort for ints and we can work on changing it for your Metoxh class.
 
Ad

Advertisements

Joined
May 6, 2021
Messages
4
Reaction score
0
i have one for int values
Java:
//Proth methodos
    
     static void mergeSort(int[] arrayToSort, int lowerIndex, int upperIndex) {
         if(lowerIndex == upperIndex)
             return;
        
         int middle = (lowerIndex + upperIndex) / 2;
         mergeSort(arrayToSort, lowerIndex , middle);
         mergeSort(arrayToSort, middle+1, upperIndex);
         merge(arrayToSort, lowerIndex, middle+1, upperIndex);
        
     }         
        
    //Deyterh methodos     
    private static void merge(int[] arrayToSort, int lowerIndexPointer,
               int higherIndex, int upperIndex) {
        
        int tempIndex = 0;
        int lowerIndex = lowerIndexPointer;
        int midIndex = higherIndex-1;
        int totalItems = upperIndex - lowerIndex+1;
        
        while(lowerIndex <= midIndex && higherIndex <= upperIndex) {
            
            if(a[lowerIndex] < a[higherIndex]) {
                arrayToSort[tempIndex++] = a[lowerIndex++];
            }else {
                arrayToSort[tempIndex++] = a[higherIndex++];
                
            }
        }
        while(lowerIndex <= midIndex) {
            arrayToSort[tempIndex++] = a[lowerIndex++];
            }
        while(higherIndex <= upperIndex) {
            arrayToSort[tempIndex++] = a[higherIndex++];
        }
        
        for(int i = 0 ; i < totalItems; i++) {
            a[lowerIndexPointer+i] = arrayToSort[i];
        }
    }
  
            
    public static Float[] convertStringArraytoFloatArray(String[] sarray) {
        Float[] intarray = null;/*from   w ww . ja va 2 s  .  c  o  m*/

        if (sarray != null) {
            intarray = new Float[sarray.length];

            try {
                for (int i = 0; i < sarray.length; i++) {
                    intarray[i] = Float.parseFloat(sarray[i]);
                }
            } catch (NumberFormatException e) {

            }
        }

        return intarray;
    }
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
28
Reaction score
6
That won't even compile, the `a` array is missing a definition. But, had it compiled, you'd just need to change where it's getting the int array in the methods:
Code:
static void mergeSort(Metoxh[] arrayToSort, int lowerIndex, int upperIndex) {

and

private static void merge(Metoxh[] arrayToSort, int lowerIndexPointer

and where it's actually making the comparison, which is only:
Code:
if(a[lowerIndex] < a[higherIndex]) {

to

if(a[lowerIndex].marks < a[higherIndex].marks) {
I tried to make it work by creating `a` as a clone of the input, but that didn't really pan out. So, you'll have to figure out what `a` is actually supposed to be or maybe the implementation is off. Either way, the way you'd modify any implementation should be the same: change where it accepts the array as input and change where it actually uses the values.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top