Advertisement
Guest User

IanClickherePlease

a guest
Apr 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. package csc355;
  2.  
  3. import java.util.Random;
  4.  
  5. public class QuickSelect
  6. {
  7.  
  8. private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot)
  9. {
  10. E pivotVal = arr[pivot];
  11. swap(arr, pivot, right);
  12. int storeIndex = left;
  13. for (int i = left; i < right; i++)
  14. {
  15. if (arr[i].compareTo(pivotVal) < 0)
  16. {
  17. swap(arr, i, storeIndex);
  18. storeIndex++;
  19. }
  20. }
  21. swap(arr, right, storeIndex);
  22. return storeIndex;
  23. }
  24.  
  25. private static <E extends Comparable<? super E>> E select(E[] arr, int n)
  26. {
  27. int left = 0;
  28. int right = arr.length - 1;
  29. Random rand = new Random();
  30. while (right >= left) {
  31. int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
  32. if (pivotIndex == n)
  33. {
  34. return arr[pivotIndex];
  35. }
  36. else if (pivotIndex < n)
  37. {
  38. left = pivotIndex + 1;
  39. } else
  40. {
  41. right = pivotIndex - 1;
  42. }
  43. }
  44. return null;
  45. }
  46.  
  47. private static void swap(Object[] arr, int i1, int i2)
  48. {
  49. if (i1 != i2)
  50. {
  51. Object temp = arr[i1];
  52. arr[i1] = arr[i2];
  53. arr[i2] = temp;
  54. }
  55. }
  56.  
  57. public static void main(String[] args)
  58. {
  59. for (int i = 0; i < 10; i++)
  60. {
  61. Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
  62. System.out.print(select(input, i));
  63. if (i < 9) System.out.print(", ");
  64. }
  65. System.out.println();
  66. }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement