Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package algoritmProgUppg1;
  2.  
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5.  
  6. public class MergeSort {
  7.  
  8. public static void mergeSort(int[] a, int lo, int hi) {
  9. int mid;
  10. if (hi > lo) {
  11. mid = lo+ (hi-lo) / 2;
  12. mergeSort(a, lo, mid);
  13. mergeSort(a, mid+1, hi);
  14. merge(a, lo, mid, hi);
  15. } else {
  16. return;
  17. }
  18. }
  19.  
  20. public static void merge(int[] a, int lo, int mid, int hi) {
  21. int[] aux = new int[a.length];
  22.  
  23. for (int i=0; i < a.length; i++) {
  24. aux[i] = a[i];
  25. }
  26.  
  27. int i = lo;
  28. int j = mid + 1;
  29.  
  30. for (int k = lo; k <= hi; k++) {
  31. if (i > mid) {
  32. a[k] = aux[j++];
  33. }
  34. else if (j > hi) {
  35. a[k] = aux[i++];
  36. }
  37. else if (aux[i] < aux[j]) {
  38. a[k] = aux[i++];
  39. } else {
  40. a[k] = aux[j++];
  41. }
  42. }
  43. }
  44.  
  45. // Checks if the first n element of a are in sorted order.
  46. private static boolean isSorted(int[] a, int lo, int hi) {
  47. int flaws = 0;
  48. for (int i = lo+1; i <= hi; i++) {
  49. if (a[i] < a[i-1]) {
  50. if (flaws++ >= 10) {
  51. System.out.println("...");
  52. break;
  53. }
  54. System.out.println("a["+i+"] = "+a[i]+", a["+(i-1)+"] = "+a[i+1]);
  55. }
  56. }
  57. return flaws == 0;
  58. }
  59.  
  60. static int[] readIntfile(String filename) throws Exception {
  61. // Read file into a byte array, and then combine every group of four bytes to an int. (Not
  62. // the standard way, but it works!)
  63. byte[] bytes = Files.readAllBytes(Paths.get(filename));
  64. int[] ints = new int[bytes.length/4];
  65. for (int i = 0; i < ints.length; i++) {
  66. for (int j = 0; j < 4; j++) { ints[i] += (bytes[i*4+j] & 255) << (3-j)*8; }
  67. }
  68. return ints;
  69. }
  70.  
  71. public static void main(String[] args) throws Exception {
  72. // int[] test = {38, 27, 43, 3, 9, 82, 10, 0, -5, 13, 999};
  73. int[] data = readIntfile("src/smallints");
  74. int N = data.length;
  75. // int N = test.length;
  76.  
  77. long before = System.currentTimeMillis();
  78. mergeSort(data, 0, N-1);
  79. long after = System.currentTimeMillis();
  80.  
  81. System.out.println((after-before)/1000);
  82. if (N <= 1000) {
  83. for (int i = 0; i < data.length; i++) { System.out.print(data[i]+" "); }
  84. System.out.print("\n");
  85. }
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement