0

My class only covered binary searching ints, which is much easier it seems. My assignment is searching Strings.

My JSON file is an already sorted list (in alphabetical order) of 20 student names and grades. I'll show one:

"Students": [
{
  "name": "Daniel",
  "id": "144586754",
  "course works":[
    {
      "name": "q1",
      "score": 9
    },{
      "name": "q2",
      "score": 5
    },{
      "name": "q3",
      "score": 7
    },{
      "name": "midterm",
      "score": 79
    },{
      "name": "final",
      "score": 57
    }
  ]

This is my attempt at my binary search:

System.out.print("Enter students name you want to find: ");
    String nameInput = command.next();
    student = new Student(nameInput);

JsonArray studentsArr = jsonObject.getJsonArray("Students");

for (JsonValue value : studentsArr) {
        int first = 1;
        int last = studentsArr.size();
        int mid;

        while (first < last) {
            mid = first + last / 2;
            if (nameInput.compareTo(studentsArr.getString(mid)) > mid) {
                first = mid + 1;
            } else {
                last = mid;
            }
            student.identify();
        }
        if (nameInput.compareTo(studentsArr.getString(first)) == first) {
            student.identify();
        }
    }

This is from trying to work off the outline from notes, and I have tried looking stuff up but do not understand how this can work with strings.

tristan
  • 5
  • 2

1 Answers1

0

This all works based off of being able to compare 2 elements and determine which is "greater". This is naturally defined in numbers.

For other items, such as Strings, you have to define how items are compared. For strings in java, it is done with the compareTo method. Once the algorithm for comparing objects is defined, you can use this basic search process to efficiently find anything in a sorted list.

eimmer
  • 1,537
  • 1
  • 10
  • 29