diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8da5f9 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +## Ex 2 + +## Function 1 +La complexité est O(n²) + +## Function 2 +La complexité est O(n) + +## Function 3 +La complexité est O(1) + +## Ex 3 +La complexité est O(1) \ No newline at end of file diff --git a/Tri.java b/Tri.java new file mode 100644 index 0000000..39b09cc --- /dev/null +++ b/Tri.java @@ -0,0 +1,83 @@ +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Comparator; + +public class Tri { + + public static void sort(Object array) { + if (array == null || !array.getClass().isArray()) { + throw new IllegalArgumentException("Un tableau est attendu."); + } + processArray(array); + } + + // renvoie la somme (long) de tous les entiers contenus dans ce sous-arbre et effectue le tri en place + private static long processArray(Object arr) { + Class cls = arr.getClass(); + if (!cls.isArray()) throw new IllegalArgumentException("Array attendu"); + + Class comp = cls.getComponentType(); + + // Feuille primitive int[] + if (comp.isPrimitive()) { + if (comp == int.class) { + int[] a = (int[]) arr; + Arrays.sort(a); + long s = 0; + for (int v : a) s += v; + return s; + } else { + throw new IllegalArgumentException("Type primitif non géré : " + comp); + } + } + + // Feuille Integer[] + if (comp == Integer.class) { + Integer[] a = (Integer[]) arr; + Arrays.sort(a); + long s = 0; + for (Integer v : a) if (v != null) s += v; + return s; + } + + // Sinon, éléments sont des sous-tableaux (ou éventuellement Number) + int n = Array.getLength(arr); + long[] sums = new long[n]; + for (int i = 0; i < n; i++) { + Object child = Array.get(arr, i); + if (child == null) { + sums[i] = 0; + } else if (child.getClass().isArray()) { + sums[i] = processArray(child); + } else if (child instanceof Number) { + sums[i] = ((Number) child).longValue(); + } else { + throw new IllegalArgumentException("Élément non géré : " + child.getClass()); + } + } + + // tri stable des éléments du tableau courant selon sums + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; i++) idx[i] = i; + Arrays.sort(idx, Comparator.comparingLong(i -> sums[i])); + + Object sorted = Array.newInstance(comp, n); + for (int k = 0; k < n; k++) { + Array.set(sorted, k, Array.get(arr, idx[k])); + } + // recopie dans arr + for (int i = 0; i < n; i++) { + Array.set(arr, i, Array.get(sorted, i)); + } + + long total = 0; + for (long v : sums) total += v; + return total; + } + + public static void main(String[] args) { + int[][] a = { {0,3,2}, {9,4,5}, {4,1,3} }; + sort(a); + System.out.println(Arrays.deepToString(a)); + } +}