waltermilner

Untitled

Dec 13th, 2018
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3.  
  4. public class Test {
  5.  
  6.  
  7.  
  8.   public static void main(String[] args) {
  9.     final int N = 50000000;
  10. int[] array = new int[N];
  11. Random rng = new Random();// fill with random values
  12. for (int counter = 0; counter < N; counter++) {
  13. array[counter] = rng.nextInt(N);
  14. //System.out.println(counter + " " + array[counter]);
  15. }
  16. quicksort(array, 0, array.length - 1); // quicksort entire array
  17. for (int counter = 0; counter < N; counter++) { // check result
  18. //System.out.println(counter + " " + array[counter]);
  19. }
  20.  
  21.   }
  22.  
  23.   public static void quicksort(int[] array, int lo, int hi) {
  24. if (lo < hi) { // if lo and hi have not become equal..
  25. int p = partition(array, lo, hi); // split. p is the split point
  26. quicksort(array, lo, p); // quicksort lower half
  27. quicksort(array, p + 1, hi); // quicksort upper half
  28. }
  29. }
  30.   static int partition(int[] array, int lo, int hi) {
  31. // work on array from index lo to hi
  32. int pivot = array[lo]; // pivot is lowest element in section
  33. int i = lo - 1; // i and j are 2 moving pointers
  34. int j = hi + 1; // i will increase and j decrease
  35. while (true) { // we break out by returning j
  36. do { // move i up until find element bigger than pivot
  37. i++;
  38. } while (array[i] < pivot);
  39. do { // move j down until find small element less than pivot
  40. j--;
  41. } while (array[j] > pivot);
  42. if (i >= j) { // if they meet..
  43. return j; // stop - we split at this position
  44. }
  45. int temp = array[i]; // else swap i and j elements
  46. array[i] = array[j];
  47. array[j] = temp; // then continue i up and j down
  48. }
  49. }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment