public class Zad_two { public static void main(String[] args) { int[] a = new int[5]; for (int k = 0; k <= a.length; k++) a[k] = (int) (Math.random() * 10); for (int k = 0; k <= a.length; k++) if (a[k] < a[k + 1]) { int t = a[k]; a[k] = a[k + 1]; a[k + 1] = t; } for (int k = 0; k < a.length; k++) // System.out.println(a[k]); } } 

Errors:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at My.Next.Step.Zad_one.main(Zad_one.java:8)

    1 answer 1

    It is necessary to write at the beginning of sorting.

     for (int k = 0; k < a.length - 1; k++) 

    PS Indeed, the sorting will not work. If this is an attempt to write a bubble algorithm, then it is necessary to write like this, for example (sorts in ascending order).

     int t; for (int k = a.length - 1; k > 0; k--) { for (int i = 0; i < k; i++) { if (a[i] > a[i+1]) { t = a[i]; a[i] = a[i+1]; a[i+1] = t; } } } 
    • all the same mistake - bagdik_wow
    • Well, yes, really, why do we need the last element =) - Specter
    • Sort exactly will not. - avp
    • theoretically all negative elements should be at the beginning of the array. swaps, but not all (I added a second random with negative numbers). - bagdik_wow
    • I created the answer myself: int temp; int [] a1 = {6, 2, -3, 7, -1, 8, 9, 0}; for (int j = 0; j <(a1.length * a1.length); j ++) {for (int i = 0; i <a1.length - 1; i ++) {if (a1 [i]> a1 [i + 1]) {temp = a1 [i]; a1 [i] = a1 [i + 1]; a1 [i + 1] = temp; }}} for (int i = 0; i <a1.length; i ++) - bagdik_wow