Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. returns 0 if a equal b
  2. returns -1 if a < b
  3. returns 1 if a > b
  4.  
  5. public void sort(Comparable[] lst)
  6. {
  7. for(int i=0; i<lst.length; i++)
  8. {
  9. for(int j=i; j<lst.length; j++)
  10. {
  11. if(lst[i].compareTo(lst[j]) < 0)
  12. {
  13. //swap elements, sorts in ascending order
  14. Comparable tmp = lst[i];
  15. lst[i] = lst[j];
  16. lst[j] = tmp;
  17. }
  18. }
  19. }
  20. }
  21.  
  22. private static <T> void binarySort(T[] a, int lo, int hi, int start, Comparator<? super T> c) {
  23. assert lo <= start && start <= hi;
  24. if (start == lo)
  25. start++;
  26. for ( ; start < hi; start++) {
  27. T pivot = a[start];
  28. // Set left (and right) to the index where a[start] (pivot) belongs
  29. int left = lo;
  30. int right = start;
  31. assert left <= right;
  32. /*
  33. * Invariants:
  34. * pivot >= all in [lo, left).
  35. * pivot < all in [right, start).
  36. */
  37. while (left < right) {
  38. int mid = (left + right) >>> 1;
  39. if (c.compare(pivot, a[mid]) < 0)
  40. right = mid;
  41. else
  42. left = mid + 1;
  43. }
  44. assert left == right;
  45. /*
  46. * The invariants still hold: pivot >= all in [lo, left) and
  47. * pivot < all in [left, start), so pivot belongs at left. Note
  48. * that if there are elements equal to pivot, left points to the
  49. * first slot after them -- that's why this sort is stable.
  50. * Slide elements over to make room for pivot.
  51. */
  52. int n = start - left; // The number of elements to move
  53. // Switch is just an optimization for arraycopy in default case
  54. switch (n) {
  55. case 2: a[left + 2] = a[left + 1];
  56. case 1: a[left + 1] = a[left];
  57. break;
  58. default: System.arraycopy(a, left, a, left + 1, n);
  59. }
  60. a[left] = pivot;
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement