Am I missing something? The source is short, ready to launch and commented out for a better understanding. I need to know what I'm doing wrong.
package com.company; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class Main { public static ArrayList<Integer> randomArrayList(int n) { ArrayList<Integer> list = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < n; i++) { list.add(random.nextInt(n)); } return list; } public static List<Integer> MergeSort(List<Integer> A) throws Exception{ if (A.size()==1) return A; int mid = A.size()/2; List<Integer> left = A.subList(0,mid); List<Integer> right = A.subList(mid,A.size()); left = MergeSort(left); right = MergeSort(right); A = Merge(left,right); return A; } public static List<Integer> Merge(List<Integer> L,List<Integer> R) throws Exception{ List<Integer> output = new ArrayList<Integer>(Collections.nCopies(L.size() + R.size(), 0)); int i = 0; int j = 0; int k = 0; while (i < L.size() && j < R.size()) { if (L.get(i) < R.get(j)) { output.set(k, L.get(i)); i=i+1; } else { output.set(k, R.get(j)); j=j+1; } k++; } while (i < L.size()) { output.set(k, L.get(i)); i=i+1; k++; } while (j < R.size()) { output.set(k, R.get(j)); j=j+1; k++; } return output; } public static List<Integer> QuickSort(List<Integer> A) throws Exception{ if (A.size()==1 || A.size()==0) return A;
In the main function, I run both methods 20 times for comparison. You can copy two sections of code and run it
public static void main(String[] args) throws Exception{ long startTime, endTime, duration;
java algorithm mergesort quicksort analysis
Eduardo A. Fernández Díaz
source share