I am trying to code quicksort in two ways, one in-place, and the other by using separate arrays. I’m kind of stuck on some of the logic, take a look at what I have, Thanks for the help in advance!
public List<Integer> sort(List<Integer> arr){
if(arr.length > 0)
List<Integer> ret = new ArrayList<Integer>();
ret = quickSort(arr);
return ret;
}
public List<Integer> quickSort(List<Integer> arr){
if(arr.length < 2)
return;
int pivot = arr[0];
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++){
if(arr[i] <= pivot)
left.add(arr[i]);
else
right.add(arr[i]);
}
quickSort(left);
quickSort(right);
}
Now i’m stuck, I don’t know what I would do after recursively going through both sets, mostly stuck on how would I connect them together and return a sorted list.
You need to combine
leftandrightsequences together. You need to do it at the end of your algorithm (before the closing}). In pseudo code:This is just a pseudo-code. You need to add code to check lengths of each array (
leftandright) in the for cycle.Also I must note that this is far from quicksort. So many
newarray allocations make the algorithm extremely slow and that’s unwelcome when sorting.Also, right side of line 3 is redundant. You don’t need to allocate anything here, as it is overwritten in the next line. I would just simply replace your lines 3-5 with this: