fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Testing
  6. {
  7. class Person implements Comparable<Person> {
  8. int cpr=200193;
  9. int age=21;
  10. String name="John Doe";
  11. String Country="Uzbekistan";
  12.  
  13. public Person() {}
  14. public Person(String name, String Country,int cpr,int age) {
  15. this.cpr=cpr;
  16. this.age=age;
  17. this.name=name;
  18. this.Country=Country;
  19. }
  20.  
  21. public String toString() {
  22. return "Person [Country= " + Country + ", Name:" + name + ", Cpr: "+cpr+ ", age: "+age+"]";
  23. }
  24.  
  25. public int compareTo(Person p) {
  26. if(p != null) {
  27. return this.age - p.age;
  28. } else throw new NullPointerException();
  29. }
  30. }
  31.  
  32. Person[] sortedArray = new Person[7];
  33. int size = -1;
  34.  
  35. boolean addToArray(Person item) {
  36.  
  37. if (item == null) {
  38. return false;
  39. } else if (size == -1) {
  40. size++;
  41. sortedArray[size] = item;
  42. return true;
  43. } else {
  44.  
  45. // find the correct position using Binary Search
  46. int insertionPoint = Arrays
  47. .binarySearch(sortedArray, 0, size+1, item);
  48. if (insertionPoint >= 0) {
  49. // duplicate value
  50. return false;
  51. }
  52.  
  53. // set the insertionPoint to proper value
  54. insertionPoint = (-(insertionPoint) - 1);
  55.  
  56. // shift
  57. for (int i = size + 1; i > insertionPoint; i--) {
  58. sortedArray[i] = sortedArray[i - 1];
  59. }
  60. // insert
  61. sortedArray[insertionPoint] = item;
  62. size++;
  63.  
  64. return true;
  65. }
  66. }
  67.  
  68. void test() {
  69. addToArray(new Person());
  70. addToArray(new Person("Pete","Germany",111111,86));
  71. addToArray(new Person("John","Denmark",123456,75));
  72. addToArray(new Person("Michael Jackson", "America",112345,49));
  73. for (int i = 0; i <= size; i++) {
  74. System.out.println(sortedArray[i]);
  75. }
  76. }
  77.  
  78. public static void main (String[] args) throws java.lang.Exception
  79. {
  80. Testing t = new Testing();
  81. t.test();
  82. }
  83. }
Success #stdin #stdout 0.07s 381248KB
stdin
Standard input is empty
stdout
Person [Country= Uzbekistan, Name:John Doe, Cpr: 200193, age: 21]
Person [Country= America, Name:Michael Jackson, Cpr: 112345, age: 49]
Person [Country= Denmark, Name:John, Cpr: 123456, age: 75]
Person [Country= Germany, Name:Pete, Cpr: 111111, age: 86]