So I have to Create a Program where the Code Reads the CSV File (csv file consists of FirstName, lastName, ID,Mark). Then after it should sort it by it self and then print how much it takes to execute the program using hte Seleciton Sort method and the Collection.sort. When I Run it.. prints.. and If I Click Running it.. after the 5th click it will say it took 16 milliseconds to do it but for most of the part it's 0.

THe Following:

Using implemented selection sort time: 0 Milliseconds
Using implemented collection sort time: 0 Milliseconds

This is My Code:

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;

    public class compareSort {

      public static void main (String [] args) {

        selectionTime ();
        collectionTime ();  
      }

      static void selectionTime () {

        ArrayList <Student> students = loadFromFile ("C:\\users\\Nilesh\\Downloads\\students.csv");

        long StartTime;
        long EndTime;

        StartTime = System.currentTimeMillis();    
        selectionSort (students);
        EndTime = System.currentTimeMillis();

        System.out.format("Using implemented selection sort time: %s Milliseconds\n", EndTime - StartTime); 

      }

      static void collectionTime () {

        ArrayList<Student> students = loadFromFile("C:\\users\\Nilesh\\Downloads\\students.csv");   

        long StartTime;
        long EndTime;

        StartTime = System.currentTimeMillis();
        Collections.sort (students);
        EndTime = System.currentTimeMillis();

        System.out.format("Using implemented collection sort time: %s Milliseconds\n",  EndTime - StartTime);

      }

      static <T extends Comparable<T>> void selectionSort ( ArrayList<T> array ) {

        for (int checkPosition = 0; checkPosition < array.size(); checkPosition ++){
          int minimumPosition = checkPosition;

          for (int i = checkPosition + 1; i < array.size(); i++ ){    
            if ( array.get(i).compareTo(array.get(minimumPosition)) < 0 ) {
              minimumPosition = i;
            }   
          }

          if (minimumPosition != checkPosition){
            swap (array, checkPosition, minimumPosition);
          }
        }
      }

      static <T> void swap ( ArrayList<T> arr, int indexA, int indexB ) {

            T temp = arr.get(indexA);
            arr.set(indexA, arr.get(indexB));
            arr.set(indexB, temp);
          } 

      static ArrayList<Student> loadFromFile( String filePath ) {

        ArrayList <Student> result = new ArrayList <Student>();

        BufferedReader bufferReader = null;
        String line = "";

        try {

        bufferReader = new BufferedReader (new FileReader(filePath));    
        line = bufferReader.readLine();    

          while ( (line = bufferReader.readLine()) != null ) {

            String[] lineSplited = line.split(","); 

            if ( lineSplited.length == 4 ) {

              String firstName = lineSplited[0];
              String lastName = lineSplited[1];
              int id = Integer.parseInt( lineSplited[2] );
              int mark = Integer.parseInt( lineSplited[3] );

              Student stu = new Student(firstName, lastName, id, mark);
              result.add(stu);          
            }
          }
        } catch (FileNotFoundException e) {
          System.out.println("File not Found");  
        } catch (IOException e) {
          System.out.println("Error While Reading the File");
        }
        finally {

          if (bufferReader != null) {
            try {
              bufferReader.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }    
        return result;
      }     


      static void printStudents( ArrayList<Student> students) {
       for (Student student : students){
        System.out.println(student);
       }   

  }  


}

Dani AI

Generated

Two separate issues are visible in the posted code: the BufferedReader is not "failing" — the first CSV row is being discarded because the code reads one line before entering the main loop — and the timing output is often 0 ms because the work is too short for System.currentTimeMillis() (plus JIT/warm‑up effects). As noted, remove the extra pre-loop read unless that first line is intentionally a header.

A safe, modern pattern is to use try-with-resources and be explicit about a header if present. For example:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
  String header = br.readLine(); // comment out if there's no header
  String row;
  while ((row = br.readLine()) != null) {
    String[] cols = row.split(",");
    // cols[i] = cols[i].trim(); parse ints with Integer.parseInt(...)
  }
}

Timing: use System.nanoTime() and average many runs to overcome timer resolution, JIT warm-up and GC noise. A simple harness:

ArrayList<Student> original = loadFromFile(path);
int runs = 200;
long totalNs = 0;
for (int i = 0; i < runs; i++) {
  ArrayList<Student> copy = new ArrayList<>(original);
  long s = System.nanoTime();
  selectionSort(copy);
  totalNs += System.nanoTime() - s;
}
System.out.printf("Average: %.3f ms%n", totalNs / (runs * 1_000_000.0));

Extra troubleshooting tips: print the first few loaded lines and the list size right after loadFromFile to verify the loader; trim fields and watch for a UTF‑8 BOM in the first token if the CSV came from Excel; consider a robust CSV parser for quoted fields and commas-in-names. Finally, keep the data set large enough for meaningful comparisons (selection sort is O(n^2), so difference grows fast).

Recommended Answers

All 3 Replies

16 mSec is 1/60 second. That's the clock resolution on simple computers. If your PC has a more accurate timer you can get it via System.nanoTime()

YOu didn't say wats wromg with your file reading, but your code will skip the first line.

What Do Mean It Skips the Line. Please Help me Fix it.

Line 82 (the main loop) you start each pass of the loop by reading the next line. That's correct, but on line 80, before the loop, you also read one line, so when you start the loop it's the second line that you read, and the first line is discarded. You just need NOT to read any lines before you start the loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.