snippetjavaMinor
Quick Sort in Java
Viewed 0 times
javasortquick
Problem
I recently started learning about algorithms and data structure's. I decided that for every algorithm I learn about I'll implement it without looking at any pseudo code or actual code.
I have implemented Quick Sort using Hoare's Partition. The pivot is the last element in the array. Can someone check and tell me if its correctly implemented. It works correctly in all cases.
Its a bit different than some of the code I saw online after I finished implementing it.
I have implemented Quick Sort using Hoare's Partition. The pivot is the last element in the array. Can someone check and tell me if its correctly implemented. It works correctly in all cases.
public class JavaApplication1 {
public static void main(String[] args) {
int arr[] = {10,9,8,7,6,5,4,3,2,1};
quickSort(arr, 0, arr.length - 1);
for (int i = 0; i pivot) {
--right;
}
if (left pivot) {
int temp_item = items[left];
items[left] = pivot;
items[endIndex] = temp_item;
}
return left;
}
}Its a bit different than some of the code I saw online after I finished implementing it.
Solution
This code is not working properly if the input array contains duplicates, and it will cause an infinite loop.
You can see it by the fact that your inner while loops do not cover equality case, left won't be increased and right won't be decreased for duplicate elements.
I believe this is a bug and not intended behavior, but if it is - consider throwing an exception when you encounter an element which equals the pivot.
Another issue is with the pivot selection. When last element is a pivot, it is easy to generate a malicious input that will cause your code to run in quadric time. An easy solution to this problem is choosing a random element and making it the pivot.
You can see it by the fact that your inner while loops do not cover equality case, left won't be increased and right won't be decreased for duplicate elements.
I believe this is a bug and not intended behavior, but if it is - consider throwing an exception when you encounter an element which equals the pivot.
Another issue is with the pivot selection. When last element is a pivot, it is easy to generate a malicious input that will cause your code to run in quadric time. An easy solution to this problem is choosing a random element and making it the pivot.
Context
StackExchange Code Review Q#135528, answer score: 3
Revisions (0)
No revisions yet.