Guest User

Untitled

a guest
Jul 19th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. public class SortTesting {
  2.  
  3. public static void main(String[] args) {
  4. int length = 10000;
  5. int[] list = new int[length];
  6. for (int i = 0; i < length; i++)
  7. list[i] = (int) (100 * Math.random());
  8. long start = System.currentTimeMillis();
  9. selectSort(list);
  10. System.out.println(System.currentTimeMillis() - start);
  11. start = System.currentTimeMillis();
  12. sort(list);
  13. System.out.println(System.currentTimeMillis() - start);
  14. }
  15.  
  16. private static int[] sort(int[] all) {
  17. if (all.length <= 1) {
  18. return all;
  19. }
  20. final int[] left = new int[all.length / 2];
  21. final int[] right = new int[all.length - left.length];
  22. System.arraycopy(all, 0, left, 0, left.length);
  23. System.arraycopy(all, left.length, right, 0, right.length);
  24. return merge(sort(left), sort(right));
  25. }
  26.  
  27. private static int[] merge(final int[] left, final int[] right) {
  28. final int[] result = new int[left.length + right.length];
  29. int leftIndex = 0, rightIndex = 0, resultIndex = 0;
  30. while (leftIndex < left.length && rightIndex < right.length) {
  31. if (left[leftIndex] < right[rightIndex]) {
  32. result[resultIndex] = left[leftIndex];
  33. leftIndex++;
  34. } else {
  35. result[resultIndex] = right[rightIndex];
  36. rightIndex++;
  37. }
  38. resultIndex++;
  39. }
  40. int[] rest;
  41. int restIndex;
  42. if (leftIndex >= left.length) {
  43. rest = right;
  44. restIndex = rightIndex;
  45. } else {
  46. rest = left;
  47. restIndex = leftIndex;
  48. }
  49. for (int i = restIndex; i < rest.length; i++) {
  50. result[resultIndex] = rest[i];
  51. resultIndex++;
  52. }
  53. return result;
  54. }
  55.  
  56. private static void selectSort(int[] list) {
  57. for (int i = 0; i < list.length - 1; i++) {
  58. int mIndex = i; // Index of smallest remaining value.
  59. for (int j = i + 1; j < list.length; j++) {
  60. if (list[mIndex] > list[j]) {
  61. mIndex = j; // Remember index of new minimum
  62. }
  63. }
  64. if (mIndex != i) {
  65. // ... Exchange current element with smallest remaining.
  66. int temp = list[i];
  67. list[i] = list[mIndex];
  68. list[mIndex] = temp;
  69. }
  70. }
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment