not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.1 KiB

  1. package net.jrtechs.www.Sorting;
  2. import net.jrtechs.www.DataStructures.Lists.ArrayList.ArrayBackedList;
  3. import java.util.Random;
  4. /**
  5. * Basic implementation of quick sort in java.
  6. *
  7. * @author Jeffery Russell
  8. * @param <E>
  9. */
  10. public class QuickSort<E extends Comparable>
  11. {
  12. /** Constant for an increasing list */
  13. public static final int INCREASING_ORDER = 1;
  14. /** Constant for a decreasing list */
  15. public static final int DECREASING_ORDER = -1;
  16. /** Type of ordering*/
  17. private int sortType;
  18. /**
  19. * Creates a new sorter with a specific ordering
  20. *
  21. * @param sortType sorting constant
  22. */
  23. public QuickSort(int sortType)
  24. {
  25. this.sortType= sortType;
  26. }
  27. /**
  28. * Wrapper function for initial call.
  29. *
  30. * @param list
  31. */
  32. public void quickSort(ArrayBackedList<E> list)
  33. {
  34. quickSort(list, 0, list.size() -1);
  35. }
  36. /**
  37. * Quick sorts the array.
  38. *
  39. * @param list array to sort
  40. * @param left left index
  41. * @param right right index
  42. */
  43. public void quickSort(ArrayBackedList<E> list, int left, int right)
  44. {
  45. if(left < right)
  46. {
  47. int pivot = partition(list, left, right);
  48. quickSort(list, left, pivot -1);
  49. quickSort(list, pivot + 1, right);
  50. }
  51. }
  52. /**
  53. * Selects a random pivot and swaps everything less than the pivot value
  54. * to the left and everything greater than the pivot to the right.
  55. *
  56. * @param list array list to sort
  57. * @param left left index
  58. * @param right right index
  59. * @return index of the sorted part
  60. */
  61. private int partition(ArrayBackedList<E> list, int left, int right)
  62. {
  63. Random random = new Random();
  64. int p = random.nextInt((right - left) + 1) + left; //select pivot
  65. list.swap(p, right);
  66. int store = left;
  67. for(int i = left; i < right; i++)
  68. {
  69. if(list.get(i).compareTo(list.get(right)) != this.sortType)
  70. {
  71. list.swap(i, store);
  72. store++;
  73. }
  74. }
  75. list.swap(store, right);
  76. return store;
  77. }
  78. }