You are on page 1of 2

Name: Stephanie Chuang

public void algorithm(int[] array){


//Incremented position from the left to push below zero values
int fromLeft = 0;
//Incremented position from the right to push above zero values
int fromRight = 0;
for(int i = 0; i < array.length; i++){
if(array[i] < 0){
swap(array[i], array[fromLeft]);
fromLeft++;
}
}
for(int i = array.length - 1; i >= 0; i--){
if(array[i] > 0){
swap(array[i], array[array.length - 1 - fromRight]);
fromRight++;
}
}
}

**implement in one pass

This algorithm is intended to organize the elements of an array such that all the values below
zero are first, followed by all zeros, followed by all the values above zero. Essentially what my
algorithm is doing is pushing all of the below zero values to the beginning of the array and
pushing all of the above zero values to the end of the array, and by default leaving all of the
zero equivalent values in the middle of the array. The variables fromLeft and fromRight
represent the sorted portions of the below and above zero values. Either value is incremented
when another value is swapped to the appropriate sides, thus the indexes from 0 to fromLeft
and fromRight to array.length - 1 are always sorted. First, the algorithm loops through the array
in a forwards direction, swapping all the below zero values it encounters to an incremented
position from the left. What results is an array with all the below zero values to the left, followed
by any combination of zero and above zero values. This must be true because the pass will
encounter every below zero value, and then switch it to a position it has already passed and is
not below zero, as it is the one increment outside of the sorted range established by the
fromLeft variable. Then, the algorithm loops through the array in a backwards direction,
swapping all the above zero values it encounters to an incremented position from the right in the
same manner as before. This results in the final array we are looking for. Since the below zero
and above zero values are pushed to the beginning and end of the array (in any order within
each group as it wasn’t specified), the zeros, if any, are left to be in the middle. If there are no
below zero values, then the above zero values will be pushed to the end of the array with no
extra consequence, and vice versa. If there are no zero values, then there’s no difference in the
sorting because once again, the below and above zero values are pushed to their respective
sides. The algorithm runs in O(n) time because there are only two passes through the array
each containing work of constant time, which is equivalent to O(2n), which is O(n).

You might also like