简体   繁体   中英

Shifting elements in an Array of objects

I need to insert an Appointment in a Planner class that takes Appointment A1 as a parameter and places A1 in proper order to an array Appoint. I have already created the Array which only has 4 default appointments and has a length of 20. I also created a method to compare two objects of the Array and return true if A1 is smaller than A2. I have a method which allows me to insert info into the Array if array[i{ = null. However I have no idea how to sort it as I have to shift elements not sort the entire array

As I have learned to code and taken more classes I've realized the answer. The array of appointments needs to be a String array and as you move into inserting new appointments compare the first three letters, then the numbers, then years. At the time I used a huge nested if else loop. As each date is a set amount of letters (3 for month, 2 day, 4 year) it is quite simple and simply push the other dates down if needed. Although I believe for this project the dates it never went above 20, I would put an error message so the code doesn't crash when being tested.

You'd better use a PriorityQueue instead of an Array . The PriorityQueue is based on a priority heap, once you add an element it will be shifted up/down the tree which takes O(log(N)) time complexity. If you shift an element in Array, it will take O(N).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM