0

I have a problem where i need to sort the record according to the date of birth. I tried to use String.comapreTo but it is only sorting by the days. not by year or month.

class Sortbydob {
    void sortString(String[] First_name, String[] Last_name, String[] Dob, int[] Percent) {
        String tempvaule;
        int temphold;
        for (int i = 0; i < 3; i++) {
            for (int j = i + 1; j < 3; j++) {
                if (Dob[i].compareTo(Dob[j]) > 0)
{
//Swapping
}


    public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            Sortbyname obj = new Sortbyname();
            String[] First_name = new String[3];
            String[] Last_name = new String[3];
            String[] Dob = new String[3];
            int[] Percent = new int[3];
            for (int i = 0; i < 3; i++) {
                System.out.println("Enter the First Name : ");
                First_name[i] = in.next();
                System.out.println("Enter the First Name : ");
                Last_name[i] = in.next();
                System.out.println("Enter the Dob in DD/MM/YYYY Format : ");
                Dob[i] = in.next();
                System.out.println("Enter the Percentage : ");
                Percent[i] = in.nextInt();

            }

so i need to take the input First and last name, DOB ,percentage and sort it based on Date of birth. Challenge is i cannot use any type of Array list or linked array or hash map or table or tree etc. Can Anyone help me to sort with basic logic?

  • You should follow the Java Naming Conventions: variable names are always written in camelCase. For example, `Last_name` should then be `lastName`. – MC Emperor Oct 09 '19 at 10:55
  • 3
    If you date format is dd/mm/yyyy, sorting in alphabetical order won't be the same as chronological order... It would be simpler to store the dates as ... dates, using the `LocalDate` class for example. – assylias Oct 09 '19 at 10:56
  • 1
    Besides, this structure is the opposite of the object-oriented paradigm. Instead of a method accepting four separate arrays, a class `Person` or something should be created with the properties `firstname`, `lastname`, `dob` and `percent`, and the method should accept an array, or even better, a `List` containing the `Person` objects to be sorted. – MC Emperor Oct 09 '19 at 11:02
  • @MCEmperor yes. but do you know how do we do in code? can you help me? –  Oct 09 '19 at 11:16
  • @assylias Can you help me with the code? How to take input and sort by DOB –  Oct 09 '19 at 11:17
  • 1
    @MCEmperor points out one design problem (more here: [Anti-pattern: parallel collections](https://codeblog.jonskeet.uk/2014/06/03/anti-pattern-parallel-collections/)). Another one is storing dates as strings. Your sorting problem comes from this. Store your dates as `LocalDate` objects and use their natural ordering for sorting, and everything will go smoothly. – Ole V.V. Oct 09 '19 at 14:50

3 Answers3

0

You need to convert the date from a String to a Date

You would need to do something like:

Date dobDate = new SimpleDateFormat("dd/mm/yyyy").parse(Dob[i]);

Once you have the dates converted to Date objects, you can sort them using the built in compare methods: after() before() equals()

Check out How to compare dates in Java? to see details

Illidanek
  • 986
  • 1
  • 17
  • 32
  • But it is showing along with time.How to Avoid it? –  Oct 09 '19 at 11:19
  • What do you mean "it is showing along with time"? You mean when you print the date? For displaying the date, you can parse it again, https://stackoverflow.com/questions/5683728/convert-java-util-date-to-string this question answers that. – Illidanek Oct 09 '19 at 11:21
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Also I don’t think your code sorts months before days of the month. – Ole V.V. Oct 09 '19 at 14:48
0

If you want it quick, you could use a recursive quicksort implementation that sorts by the String part representing years first, then months, then days. In the following example, you have to provide the positions of the year (yyyy), the month (MM) and the day (dd) as well as the character that delimits them in the date format pattern:

public static void main(String[] args) {
        String[] birthdays = { 
            "10/05/1990",
            "10/05/2001",
            "10/05/2006",
            "10/05/1960",
            "10/05/2033" 
    };

    // print the unsorted array (build up one-line representation first)
    StringBuilder unsortedBirthdaysBuilder = new StringBuilder();
    for (int i = 0; i < birthdays.length; i++) {
        if (i != 0) {
            unsortedBirthdaysBuilder.append(", ");
        }
        unsortedBirthdaysBuilder.append(birthdays[i]);
    }
    System.out.println("unsorted:\t" + unsortedBirthdaysBuilder.toString());

    // do the sorting
    quickBirthdaySort(birthdays, "/", 2, 1, 0);

    // print the sorted array (build up one-line representation first)
    StringBuilder sortedBirthdaysBuilder = new StringBuilder();
    for (int i = 0; i < birthdays.length; i++) {
        if (i != 0) {
            sortedBirthdaysBuilder.append(", ");
        }
        sortedBirthdaysBuilder.append(birthdays[i]);
    }
    System.out.println("sorted:\t\t" + sortedBirthdaysBuilder.toString());
}

public static void quickBirthdaySort(String[] birthdays, String delimiter,
        int yearPatternPosition, int monthPatternPosition,
        int dayPatternPosition) {
    String temp;
    int a, b, c, d, e, f;

    for (int i = 0; i < birthdays.length - 1; i++) {
        // sort by years first
        a = Integer.valueOf(birthdays[i].split(delimiter)[yearPatternPosition]);
        b = Integer.valueOf(birthdays[i + 1].split(delimiter)[yearPatternPosition]);
        if (a > b) {
            temp = birthdays[i];
            birthdays[i] = birthdays[i + 1];
            birthdays[i + 1] = temp;
            quickBirthdaySort(birthdays, delimiter, yearPatternPosition,
                    monthPatternPosition, dayPatternPosition);
        } else if (a == b) {
            // then sort by months
            c = Integer.valueOf(birthdays[i].split(delimiter)[monthPatternPosition]);
            d = Integer.valueOf(birthdays[i + 1].split(delimiter)[monthPatternPosition]);
            if (c > d) {
                temp = birthdays[i];
                birthdays[i] = birthdays[i + 1];
                birthdays[i + 1] = temp;
                quickBirthdaySort(birthdays, delimiter, yearPatternPosition,
                        monthPatternPosition, dayPatternPosition);
            } else if (c == d) {
                // finally sort by days
                e = Integer.valueOf(birthdays[i].split("-")[dayPatternPosition]);
                f = Integer.valueOf(birthdays[i + 1].split("-")[dayPatternPosition]);
                if (e > f) {
                    temp = birthdays[i];
                    birthdays[i] = birthdays[i + 1];
                    birthdays[i + 1] = temp;
                    quickBirthdaySort(birthdays, delimiter, yearPatternPosition,
                            monthPatternPosition, dayPatternPosition);
                }
            }
        }
    }
}

The output of this code is the following:

unsorted:   10/05/1990, 10/05/2001, 10/05/2006, 10/05/1960, 10/05/2033
sorted:     10/05/1960, 10/05/1990, 10/05/2001, 10/05/2006, 10/05/2033

The positions of the date parts are given as array indexes, virtually as if the String was already split by the delimiter. For this example, I have taken the positions from your pattern (dd/MM/yyyy).

Please note that I haven't compared its runtime to any alternative, that's your part, especially because you didn't give any comparison data for the runtime.
Also note that this just sorts Strings. You have to use this for sorting your objects.

deHaar
  • 11,298
  • 10
  • 32
  • 38
0

Something you can do is taking a sub-string of the date in years,months and days, parse them to Integers and compare them. here is my code:

public static void sortString(String[] Dob) {
    for (int i = 0; i < 3; i++) {
        for (int j = i + 1; j < 3; j++) {

            //getting the strings of the years/months/days
            String yearA = Dob[i].substring(6, 10);
            String yearB = Dob[j].substring(6, 10);
            String monthA = Dob[i].substring(3, 5);
            String monthB = Dob[j].substring(3, 5);
            String dayA = Dob[i].substring(0, 2);
            String dayB = Dob[j].substring(0, 2);

            //converting to Integers
            int yearAnum = Integer.parseInt(yearA);
            int yearBnum = Integer.parseInt(yearB);
            int monthAnum = Integer.parseInt(monthA);
            int monthBnum = Integer.parseInt(monthB);
            int dayAnum = Integer.parseInt(dayA);
            int dayBnum = Integer.parseInt(dayB);

            //sorting
            if (yearBnum<yearAnum)
            {
                //Swapping
                String temp = Dob[i];
                Dob[i] = Dob[j];
                Dob[j]=temp;
            }
            else if (yearBnum==yearAnum)
            {
                if (monthBnum<monthAnum)
                {
                    //Swapping
                    String temp = Dob[i];
                    Dob[i] = Dob[j];
                    Dob[j]=temp;
                }
                else if (monthBnum == monthAnum)
                {
                    if (dayBnum<dayAnum)
                    {
                        //Swapping
                        String temp = Dob[i];
                        Dob[i] = Dob[j];
                        Dob[j]=temp;
                    }
                    else
                        ;
                }
                else
                    ;
            }
            else
                ;
        }}}
NirF
  • 197
  • 5