Merge Sort
import java.util.Arrays; public class MergeSort{ public static void merge(int[] a,int left, int mid, int right) { int temp [] =new int[right-left+1]; int i = left; int j = mid+1; int k = 0; while (i <= mid && j <= right) { if (a[i] <= a[j]) { temp[k++] = a[i++]; } else { temp[k++] = a[j++]; } } while(j<=right) temp[k++]=a[j++]; while(i<=mid) temp[k++]=a[i++]; for(k=0;k<temp.length;k++) a[left+k]=temp[k]; } public static void mergesort(int[] a,int left,int right){ if(left==right){ return; } else{ int mid=(left+right)/2; mergesort(a,left,mid); mergesort(a,mid+1,right); merge(a,left,mid,right); } } public static void main(String[] args){ int[] input = {2,2,435,33,3,3,3,56,6,6,7,8,3,6,9,8,6}; System.out.println("Before: "+Arrays.toString(input)); mergesort(input,0,input.length-1); System.out.println("After: "+Arrays.toString(input)); } } /* Before: [2, 2, 435, 33, 3, 3, 3, 56, 6, 6, 7, 8, 3, 6, 9, 8, 6] After: [2, 2, 3, 3, 3, 3, 6, 6, 6, 6, 7, 8, 8, 9, 33, 56, 435] */
0 comments:
Post a Comment