Advertisement
Manioc

qsort

May 7th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. package sorting.divideAndConquer;
  2.  
  3.  
  4. import java.util.Collections;
  5. import java.util.Random;
  6. import java.util.concurrent.ThreadLocalRandom;
  7.  
  8. import sorting.AbstractSorting;
  9. import util.*;
  10. /**
  11.  * Quicksort is based on the divide-and-conquer paradigm. The algorithm chooses
  12.  * a pivot element and rearranges the elements of the interval in such a way
  13.  * that all elements lesser than the pivot go to the left part of the array and
  14.  * all elements greater than the pivot, go to the right part of the array. Then
  15.  * it recursively sorts the left and the right parts. Notice that if the list
  16.  * has length == 1, it is already sorted.
  17.  */
  18. public class QuickSort<T extends Comparable<T>> extends AbstractSorting<T> {
  19.    
  20.    
  21.     public void shuffle(T[] array){
  22.         Random rnd = ThreadLocalRandom.current();
  23.         for (int i = array.length - 1; i > 0; i--){
  24.           int index = rnd.nextInt(i + 1);
  25.           T valor = array[index];
  26.           array[index] = array[i];
  27.           array[i] = valor;
  28.         }
  29.      }
  30.  
  31.     public void qsort(T[] array, int leftIndex, int rightIndex) {
  32.         if(leftIndex < rightIndex && leftIndex >= 0 && rightIndex < array.length) {
  33.             T pivot = array[rightIndex];
  34.             int divisor = leftIndex-1;
  35.             for(int j = leftIndex; j <= rightIndex-1; j++) {
  36.                 if(array[j].compareTo(pivot) <= 0) {
  37.                     Util.swap(array, ++divisor, j);
  38.                 }
  39.             }
  40.             Util.swap(array, ++divisor, rightIndex);
  41.             qsort(array, leftIndex, divisor-1);
  42.             qsort(array, divisor+1, rightIndex);
  43.         }
  44.     }
  45.    
  46.     @Override
  47.     public void sort(T[] array, int leftIndex, int rightIndex) {
  48.         shuffle(array);
  49.         qsort(array, leftIndex, rightIndex);
  50.     }
  51.    
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement