Above is the question. I was able to figure out all of the other methods in my c
ID: 3777083 • Letter: A
Question
Above is the question. I was able to figure out all of the other methods in my class but I cannot get this one for the life of me. The method should return the partition index, which is the first number in the sorted array. Here is my code:
public class ArrayHelper {
public static int sortIntoGroups(int[] arrayToSort, int partitionValue) {
int[] sortedArray = new int[arrayToSort.length];
int partitionIndex = 0;
int[] firstGroup = new int[arrayToSort.length];
int[] secondGroup = new int[arrayToSort.length];
for (int i=0; i<arrayToSort.length; i++) {
if (arrayToSort[i] < partitionValue) {
firstGroup[i]=arrayToSort[i];
}
else if (arrayToSort[i] >= partitionValue) {
secondGroup[i]=arrayToSort[i];
}
do {
firstGroup[i]=sortedArray[i];
} while (firstGroup[i]!=0);
do {
secondGroup[i]=sortedArray[i];
} while (sortedArray[i] == 0 && secondGroup[i]!=0);
}
partitionIndex = sortedArray[0];
return partitionIndex;//returning 0
}
}
Explanation / Answer
Since sortedArray is initialized with '0' and not modified throughout the program. Since partitionIndex value is initialized with sortedArray[0] which will be '0' the return value partitionIndex value will be '0' everytime. And the modified program is given below
public class SimpleRead
{
public static void main( String [] args )
{
int[] arr=new int[3];
int part=2;
arr[0]=5;
arr[1]=7;
arr[2]=1;
ArrayHelper a=new ArrayHelper();
System.out.println(a.sortIntoGroups(arr,part));
}
}
class ArrayHelper {
public static int sortIntoGroups(int[] arrayToSort, int partitionValue) {
int[] sortedArray = new int[arrayToSort.length];
int partitionIndex = 0;
int j=0;
int[] firstGroup = new int[arrayToSort.length];
int[] secondGroup = new int[arrayToSort.length];
for (int i=0; i<arrayToSort.length; i++) {
if (arrayToSort[i] < partitionValue) {
firstGroup[i]=arrayToSort[i];
}
else if (arrayToSort[i] >= partitionValue) {
secondGroup[i]=arrayToSort[i];
}
if(firstGroup[i]!=0)
sortedArray[j++]=firstGroup[i];
else if(sortedArray[i]!=0)
sortedArray[j++]=secondGroup[i];
}
partitionIndex = sortedArray[0];
return partitionIndex; //return the first occurence of value which is less than the paritionvalue
}
}