Add Entiers code exercice.
[TP_POO.git] / Entiers / Entiers.java
1
2 class Entiers {
3 private int int_array[];
4 private int array_size;
5 private int current_size;
6
7 private void setSize(int size) {
8 array_size = size;
9 }
10
11 private int getSize() {
12 return array_size;
13 }
14
15 private void setCurrentSize(int index) {
16 current_size = index;
17 }
18
19 private int getCurrentSize() {
20 return current_size;
21 }
22
23 Entiers(int size) {
24 int_array = new int[size];
25 setSize(size);
26 setCurrentSize(0);
27 }
28
29 public boolean inserer(int value) {
30 if (is_full()) {
31 System.out.println("Tableau plein");
32 return false;
33 }
34 //FIXME: Avoid duplicated values
35 int i;
36 for (i = getCurrentSize() - 1; (i >= 0 && int_array[i] > value); i--) {
37 int_array[i + 1] = int_array[i];
38 }
39 int_array[i + 1] = value;
40 current_size++;
41 return true;
42 }
43
44 private int binarySearch(int first, int last, int value) {
45 if (last < first)
46 return -1;
47 int middle = (first + last) / 2;
48 if (value == int_array[middle])
49 return middle;
50 if (value > int_array[middle])
51 return binarySearch((middle + 1), last, value);
52 return binarySearch(first, (middle -1), value);
53 }
54
55 public boolean supprimer(int value) {
56 if (is_empty()) {
57 System.out.println("Aucune valeur à supprimer");
58 return false;
59 }
60
61 // Find position of element to be deleted
62 int pos = binarySearch(0, getCurrentSize(), value);
63
64 if (pos == -1)
65 {
66 System.out.println("Valeur à supprimer inexistante");
67 return false;
68 }
69
70 // Deleting element
71 for (int i = pos; i < getCurrentSize() - 1; i++) {
72 int_array[i] = int_array[i + 1];
73 }
74
75 current_size--;
76 return true;
77 }
78
79 private boolean is_full() {
80 return (getCurrentSize() >= getSize());
81 }
82
83 private boolean is_empty() {
84 return (getCurrentSize() == 0);
85 }
86
87 public void afficher() {
88 for (int i = 0; i < getSize(); i++) {
89 System.out.println("element " + i + " " + int_array[i]);
90 }
91 }
92
93 public static void main(String[] args) {
94 Entiers integer = new Entiers(5);
95
96 integer.inserer(1);
97
98 integer.afficher();
99
100 integer.inserer(12);
101
102 integer.afficher();
103
104 integer.inserer(3);
105
106 integer.afficher();
107
108 integer.inserer(0);
109
110 integer.inserer(1);
111
112 integer.afficher();
113
114 integer.supprimer(12);
115
116 integer.afficher();
117 System.out.println("Current size " + integer.getCurrentSize());
118
119 integer.supprimer(1);
120
121 integer.afficher();
122 System.out.println("Current size " + integer.getCurrentSize());
123
124
125 }
126 }