Write a method named sweep
that accepts an array of integers as a parameter and performs a single "sweep" over the array from lowest to highest index, comparing adjacent elements. If a pair of adjacent elements are out of order (if the element at the lower index has a greater value than the element at the higher index), your method should swap them. For example, in an array of 6 elements, your method first examines elements at indexes 0-1, then 1-2, then 2-3, 3-4, and 4-5, swapping if they are out of order. One side effect of this method is that the single element with the largest value will be moved into the final index of the array. (Repeated "sweeping" can be used to sort an array.)
If your method ends up swapping any elements, it should return true
to indicate that the array was changed. Otherwise (if the array was already in ascending order before the sweep), it should return false
.
The table below shows calls to your method and the array contents after the method is finished executing:
Array / Call |
Contents of Array After Call |
Value Returned |
int[] a1 = {1, 6, 2, 7, 3, 6, 4};
sweep(a1);
|
{1, 2, 6, 3, 6, 4, 7}
|
true
|
int[] a2 = {9, 4, 2, 1, 3, 12, 14, 6, 8};
sweep(a2);
|
{4, 2, 1, 3, 9, 12, 6, 8, 14}
|
true
|
int[] a3 = {3, 4, 8, 2, 1, 8, 8, 4, 12};
sweep(a3);
|
{3, 4, 2, 1, 8, 8, 4, 8, 12}
|
true
|
int[] a4 = {-1, -4, 17, 4, -1};
sweep(a4);
|
{-4, -1, 4, -1, 17}
|
true
|
int[] a5 = {2, 3, 5, 7, 11, 13};
sweep(a5);
|
{2, 3, 5, 7, 11, 13}
|
false
|
int[] a6 = {42};
sweep(a6);
|
{42}
|
false
|
You may assume that the array contains at least one element (its length is at least 1). Do not make assumptions about the values of the elements in the array; they could be very large or small, etc.