Merge Sort (Generic)

import java.util.*; public class Sorts { public static <T extends Comparable<T>> ArrayList<T> mergeSort(ArrayList<T> list){ ArrayList<T> listaOrdenada, right, left; right = new ArrayList<T>(); left = new ArrayList<T>(); listaOrdenada = new ArrayList<T>(); if(list.size() <= 1) return list; else{ int middle = list.size()/2; for(int x = 0; x <= middle -1; x++) left.add(list.get(x)); for(int y = middle; y < list.size(); y++) right.add(list.get(y)); left = mergeSort(left); right = mergeSort(right); if(left.get(left.size()-1).compareTo(right.get(0)) <= 0){ left.addAll(right); return left; } listaOrdenada = mergeS(left, right); return listaOrdenada; } } public static <T extends Comparable<T>> ArrayList<T> mergeS(ArrayList<T> left, ArrayList<T> right){ ArrayList<T> result = new ArrayList<T>(); while(left.size() > 0 && right.size() > 0){ if(left.get(0).compareTo(right.get(0)) <= 0) result.add(left.remove(0)); else result.add(right.remove(0)); } if(left.size() > 0) result.addAll(left); if(right.size() > 0) result.addAll(right); return result; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.