publicclass MergeSort { publicstaticvoid sort(Object[] arr) { //create a temporary array to store partitioned elements Object[] tempArr = arr.clone(); //call msort with arrays arr and tempArr along //with the index range msort(arr, tempArr, 0, arr.length); } publicstatic<T extends Comparable<?super T>>void sort(T[] arr) { //create a temporary aray to store partitioned elements T[] tempArr = (T[]) arr.clone(); //call msort with arrays arr and tempArr along //with the index range msort(arr, tempArr, 0, arr.length); } privatestaticvoid msort(Object[] arr, Object[] tempArr, int first, int last) { //if the sublist has more than 1 element continue if (first +1< last) { //for sublists of size 2 or more, call msort() //for the left and right sublists and than //merge the sorted sublists using merge() int midpt = (last + first) /2; msort(arr, tempArr, first, midpt); msort(arr, tempArr, midpt, last); //if list is already sorted, just copy src to //dest; this is an optimization that results in faster //sorts for nearly ordered lists if (((Comparable) arr[midpt -1]).compareTo(arr[midpt]) <=0) return; //the elements in the ranges [first,mid] and //[mid,last] are ordered;merge the ordered sublists //into an ordered sequence in the range [first , last] //using the temporary array int indexA, indexB, indexC; //set indexA to scan sublist A with rang [first , mid] //and indexB to scan sublist B with rang [mid , last] indexA = first; indexB = midpt; indexC = first; //while both sublists are not exhausted, compare //arr[indexA] and arr[indexB]; copy the smaller //to tempArr while (indexA < midpt && indexB < last) { if (((Comparable) arr[indexA]).compareTo(arr[indexB]) <0) { tempArr[indexC] = arr[indexA]; //copyto tempArr indexA++; //increment indexA }else{ tempArr[indexC] = arr[indexB]; //copyto tempArr indexB++; //increment indexB } indexC++; //increment indexC } //copy the tail of the sublist that is not exhausted while (indexA < midpt) { tempArr[indexC++] = arr[indexA++]; //copy to tempArr }while (indexB < last) { tempArr[indexC++] = arr[indexB++]; //copy to tempArr } //copy elements form temporary array to original array for (int i = first; i < last; i++) arr[i] = tempArr[i]; } } }
publicclass InsertSort { //sort an array of elements using insertion sort publicstatic<T extends Comparable<?super T>>void sort(T[] arr) { int i, j, n = arr.length; T target; /** *//** * place element at index i into the sublist * from index 0 to i-1 where 1<= i, * so it is in the correct positon */ for (i =1; i < n; i++) { //index j scans down list from index i looking for //correct position to locate target; assigns it to //arr at index j j = i; target = arr[i]; //locate insertion point by scanning downward as long //as target < arr[j] and we have not encountered the //beginning of the array while (j >0&& target.compareTo(arr[j -1]) <0) { //shift elements up list to make room for insertion arr[j] = arr[j -1]; j--; } //the location is found;insert target arr[j] = target; } } }