Computer Applications

Sam performs bubble sort on the following array to organise the elements in ascending order:
{5, 1, 2, 3}

After the first comparison the array is:
{1, 5, 2, 3}

What would be the array after the next comparison?

  1. {1, 2, 5, 3}
  2. {1, 5, 3, 2}
  3. {1, 3, 5, 2}
  4. {1, 3, 2, 5}

Java Arrays

2 Likes

Answer

{1, 2, 5, 3}

Reason — In Bubble Sort, adjacent elements are compared and swapped if they are in the wrong order.

Original array: {5, 1, 2, 3}
After the first comparison (compare 5 and 1):
Since 5 > 1, they are swapped → {1, 5, 2, 3}

Next comparison (second comparison):
Compare 5 and 2. Since 5 > 2, they are swapped → {1, 2, 5, 3}

So, after the next comparison, the array becomes {1, 2, 5, 3}.

Answered By

1 Like


Related Questions