合并排序包括将数组递归分为两部分,进行排序,最后合并它们。合并排序的一种变体被视为3向合并排序,其中不是将数组分为2部分,而是将其分为3部分。
合并排序以递归方式将数组分解为大小为一半的子数组。同样,三向合并排序会将数组分解为大小为三分之一的子数组。
Input : 46, -1, -44, 79, 31, -41, 11, 20 , 74, 94 Output : -44 -41 -1 11 20 31 46 74 79 94 Input : 24, -18 Output : -18 24
3路合并排序的时间复杂度为nlog 3 n。
// C++ Program for performing 3 way Merge Sort #include <bits/stdc++.h> usingnamespacestd; voidmerge1(intgArray1[], intlow1, intmid1, intmid2, inthigh1, intdestArray1[]){ inti = low1, j = mid1, k = mid2, l = low1; //在三个范围中选择较小的 while((i < mid1) && (j < mid2) && (k < high1)){ if(gArray1[i] < gArray1[j]){ if(gArray1[i] < gArray1[k]){ destArray1[l++] = gArray1[i++]; } else{ destArray1[l++] = gArray1[k++]; } } else{ if(gArray1[j] < gArray1[k]){ destArray1[l++] = gArray1[j++]; } else{ destArray1[l++] = gArray1[k++]; } } } while((i < mid1) && (j < mid2)){ if(gArray1[i] < gArray1[j]){ destArray1[l++] = gArray1[i++]; } else{ destArray1[l++] = gArray1[j++]; } } while((j < mid2) && (k < high1)){ if(gArray1[j] < gArray1[k]){ destArray1[l++] = gArray1[j++]; } else{ destArray1[l++] = gArray1[k++]; } } while((i < mid1) && (k < high1)){ if(gArray1[i] < gArray1[k]){ destArray1[l++] = gArray1[i++]; } else{ destArray1[l++] = gArray1[k++]; } } while(i < mid1) destArray1[l++] = gArray1[i++]; while(j < mid2) destArray1[l++] = gArray1[j++]; while(k < high) destArray1[l++] = gArray1[k++]; } voidmergeSort3WayRec(intgArray1[], intlow1, inthigh1, intdestArray1[]){ if(high1 - low1 < 2) return; intmid1 = low1 + ((high1 - low1) / 3); intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1; mergeSort3WayRec(destArray1, low1, mid1, gArray1); mergeSort3WayRec(destArray1, mid1, mid2, gArray1); mergeSort3WayRec(destArray1, mid2, high1, gArray1); merge(destArray1, low1, mid1, mid2, high1, gArray1); } voidmergeSort3Way(intgArray1[], intn1){ if(n1 == 0) return; intfArray1[n]; for(inti = 0; i < n1; i++) fArray1[i] = gArray1[i]; //排序功能 mergeSort3WayRec(fArray1, 0, n, gArray1); for(inti = 0; i < n1; i++) gArray1[i] = fArray1[i]; } //驱动程式码 intmain(){ intdata1[] = {46, -1, -44, 79, 31, -41, 11, 20, 74, 94}; mergeSort3Way(data1,10); cout<< "After 3 way merge sort: "; for(inti = 0; i < 10; i++){ cout<< data1[i] << " "; } return0; }
输出结果
After 3 way merge sort: -44 -41 -1 11 20 31 46 74 79 94