logo Practice-It logo

sweep

Language/Type: Java arrays
Author: Marty Stepp

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.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.