Challenge: Swap and Sort

Complete the swapping and sorting an array challenge.

We'll cover the following

Swap counter in the sorting technique

This simplest and easiest sorting technique is used far and wide in computer science. It relies on comparisons of adjacent values and ultimately sorts the complete array.

Let’s take (1,2,3) as the array to be sorted in descending order. Here are a series of steps to implement:

  1. (1,2,3)(2,1,3)
  2. (2,1,3)(2,3,1)
  3. (2,3,1)(3,2,1)

Write Java code to return the minimum number of swaps required for this sorting method.

For example, if {7, 7, 5, 0, 1} is the input array to be sorted, your code should return the following output:

1

The result of 1 indicates that only one swap was needed to sort the array: {7, 7, 5, 1, 0}.

Note: Don’t worry if you need help. You can see the solution by pressing the “Show Solution” button.

Get hands-on with 1200+ tech skills courses.