Objectifs exercice 3
- Manipulation plus complexe de tableau
Travail à faire
Écrivez une fonction isSorted prenant un tableau en argument et qui retourne -1 si les éléments du tableau sont dans l’ordre croissant et l’indice du premier élément non trié autrement.
Exemple:
double[] a = {1.2, 3.2, 4.4, 5.5}
double[] b = {1.2, 2.1, 3.3, 2.5, 4.5}
isSorted(a); // returns -1, the array is sorted
isSorted(b); // returns 3, as 2.5 is < than 3.3
Une solution possible
public static int isSorted(int[] a) {
// an array of size 0 or 1 is always sorted
if(a.length <= 1)
return -1;
// Note how we stop at length - 1 so we can
// compare every element by pairs
for (int i = 0; i < a.length-1; i++) {
if(a[i] > a[i+1])
return i;
}
return -1;
}
