guys, I have the following merge sort algorithm, and I'm trying to count the number of comparison that is has to do in order to sort the whole array. I know the formula, I just don't know where to put the counter since it is a recursive algorithm... could someone shed some light on this. Thanks
//sorting array using merge sort static void mergeSort(int[] a) { if(a.length > 2) { int mid = a.length / 2; int[] first = new int[mid]; int[] second = new int[a.length - mid]; for(int i = 0; i < first.length; i++) { first[i] = a[i]; } for(int i = 0; i < second.length; i++) { second[i] = a[mid+i]; } mergeSort(first); mergeSort(second); merge(first, second, a); } } //merging first and second halfs of mergeSort array static void merge(int[] first, int[] second, int[] a) { int iFirst = 0; int iSecond = 0; int i = 0; //moving the smaller element into a while(iFirst < first.length && iSecond < second.length) { if(first[iFirst] < second[iSecond]) { a[i] = first[iFirst]; iFirst++; } else { a[i] = second[iSecond]; iSecond++; } i++; mergeCounter += i; } //copying the remaning of the first array while(iFirst < first.length) { a[i] = first[iFirst]; iFirst++; i++; } //copying the remaining of second array while(iSecond < second.length) { a[i] = second[iSecond]; iSecond++; i++; } }