Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Sorter
- {
- //Swap helper method.
- public static void swap(int [] items, int index_one, int index_two)
- {
- int temp = items[index_one];
- items[index_one] = items[index_two];
- items[index_two] = temp;
- }
- //Overloaded method name.
- public static void quicksort(int [] nums)
- {
- quicksort(nums, 0, nums.length - 1);
- }
- //Sorter recursive method, items[segment_begining] used as pivot value.
- public static void quicksort(int [] items, int segment_begining, int segment_end)
- {
- if(segment_end - segment_begining >= 2) //Do if length of the segment is more than or equal to two.
- {
- int boundary = segment_begining; //Index which will which will separate portions of array.
- int iterator = boundary + 1; //Index which will be used to iterate and swap.
- while(iterator <= segment_end) //Do for as long as iterator hasn't reached the end of segment.
- {
- if(items[iterator] <= items[segment_begining]) //If number at [iterator] is less than or equal to the number at the [segment_beginning], the pivot.
- {
- swap(items, boundary + 1, iterator); //Swap number at index one more than [boundary] and [iterator].
- boundary++; //Increment boundary to mark new position of the sorted segment.
- }
- iterator++; //Increment iterator, move to the next element.
- }
- swap(items, boundary, segment_begining); //Swap [boundary] with [segment_beginning] in order to move pivot to correct index.
- quicksort(items, boundary + 1, segment_end); //Pivot value at correct index ..x<pivot<y.., do the recursive calls.
- quicksort(items, segment_begining, boundary - 1); //Sort items at less than pivot index and more than pivot index. //Sort items at more than pivot index.
- }
- }
- }
Add Comment
Please, Sign In to add comment