From: Jérôme Benoit Date: Tue, 13 Feb 2018 20:08:49 +0000 (+0100) Subject: Entiers: Optimize the add and remove function: X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=61363e13bcb2f16fe37e13dfd59ee04719934e4f;p=TP_POO.git Entiers: Optimize the add and remove function: Avoid to loop over the tab elements twice. Signed-off-by: Jérôme Benoit --- diff --git a/Entiers/Entiers.java b/Entiers/Entiers.java index fe92652..7251eb5 100644 --- a/Entiers/Entiers.java +++ b/Entiers/Entiers.java @@ -27,21 +27,33 @@ class Entiers { } public boolean inserer(int value) { - if (is_full()) { + if (isFull()) { System.out.println("Tableau plein"); return false; } - int pos = binarySearch(0, getCurrentSize(), value); - if (pos != -1) - { - System.out.println("Valeur à inserer déjà présente"); - return false; - } - int i; - for (i = getCurrentSize() - 1; (i >= 0 && int_array[i] > value); i--) { - int_array[i + 1] = int_array[i]; + if (isEmpty()) { + int_array[0] = value; + current_size++; + return true; + } else { + for (int i = 0; i < getCurrentSize(); i++) { + if (int_array[i] == value) { + return true; + } else if (int_array[i] > value) { + for (int j = getCurrentSize(); j > i; j--) { + int_array[j] = int_array[j - 1]; + } + int_array[i] = value; + current_size++; + return true; + } + } } - int_array[i + 1] = value; + /** + * The current value to add is > to all elements in the tab. + * So add it at the end. + */ + int_array[getCurrentSize()] = value; current_size++; return true; } @@ -58,38 +70,34 @@ class Entiers { } public boolean supprimer(int value) { - if (is_empty()) { + if (isEmpty()) { System.out.println("Aucune valeur à supprimer"); return false; } - // Find position of element to be deleted - int pos = binarySearch(0, getCurrentSize(), value); - - if (pos == -1) - { - System.out.println("Valeur à supprimer inexistante"); - return false; - } - - // Deleting element - for (int i = pos; i < getCurrentSize() - 1; i++) { - int_array[i] = int_array[i + 1]; - } - - current_size--; - return true; + for (int i = 0; i < getCurrentSize(); i++) { + if (int_array[i] == value) { + // Deleting the element in the tab + for (int j = i; j < getCurrentSize() - 1; j++) { + int_array[j] = int_array[j + 1]; + } + current_size--; + return true; + } + } + return true; } - private boolean is_full() { + private boolean isFull() { return (getCurrentSize() >= getSize()); } - private boolean is_empty() { + private boolean isEmpty() { return (getCurrentSize() == 0); } public void afficher() { + System.out.println("----"); for (int i = 0; i < getSize(); i++) { System.out.println("element " + i + " " + int_array[i]); }