Sorting

AP Computer Science A· difficulty 3/5

int[] a = {4, 2, 5, 1};
for (int i = 0; i < a.length - 1; i++) {
  for (int j = 0; j < a.length - 1 - i; j++) {
    if (a[j] > a[j+1]) {
      int t = a[j]; a[j] = a[j+1]; a[j+1] = t;
    }
  }
}

What is the array after one full pass of the inner loop (i=0)?

  • A

    {2, 1, 4, 5}

  • B

    {1, 2, 4, 5}

  • C

    {2, 4, 1, 5}

    check_circle
  • D

    {4, 2, 1, 5}

Explanation

First pass bubbles 5 to the end: {4,2,5,1}->{2,4,5,1}->{2,4,5,1}->{2,4,1,5}.

Want 10 more like this — adaptive to your weak spots?

Related questions