# Java 中的icode9就地合并排序

2022-11-27 15:31:49  阅读：105  来源： 互联网

# 普通就地合并排序

``````
class PlainInPlaceMergeSort {
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}

private void inPlaceMerge(int[] nums, int start, int mid, int end) {
int leftPointer = start;
int rightPointer = mid + 1;
while (leftPointer <= mid && rightPointer <= end) {
if (nums[leftPointer] <= nums[rightPointer]) {
leftPointer++;
} else {
int currentRightElement = nums[rightPointer];
int currentRightPointer = rightPointer;
while (currentRightPointer > leftPointer) {
nums[currentRightPointer] = nums[currentRightPointer - 1];
currentRightPointer--;
}
nums[leftPointer] = currentRightElement;
leftPointer++;
rightPointer++;
mid++;
}
}
}

private int getMid(int start, int end) {
return start + (end - start) / 2;
}

private void inPlaceMergeSortHelper(int[] nums, int start, int end) {
if(end - start < 2) {
return;
}
int mid = getMid(start, end);
inPlaceMergeSortHelper(nums, start, mid);
inPlaceMergeSortHelper(nums, mid + 1, end);
inPlaceMerge(nums, start, mid, end);
}

public void inPlaceMergeSort(int[] nums) {
inPlaceMergeSortHelper(nums, 0, nums.length - 1);
}
}
``````

# 外壳排序 就地混合合并排序

``````
class ShellSortMixedInplaceMergeSort {
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}

private void inPlaceMerge(int[] nums, int start, int end) {
int length = end - start + 1;
int comparisonRange = getComparisonRange(length);
while (comparisonRange >= 1) {
int pointer = start;
while (pointer + comparisonRange <= end) {
if (nums[pointer] > nums[pointer + comparisonRange]) {
swap(nums, pointer, pointer + comparisonRange);
}
pointer++;
}
if(comparisonRange == 1) {
break;
}
comparisonRange = getComparisonRange(comparisonRange);
}
}

private int getComparisonRange(int previousLength) {
return (int) Math.ceil((double) previousLength / 2);
}

private int getMid(int start, int end) {
return start + (end - start) / 2;
}

private void inPlaceMergeSortHelper(int[] nums, int start, int end) {
if (end - start < 1) {
return;
}
int mid = getMid(start, end);
inPlaceMergeSortHelper(nums, start, mid);
inPlaceMergeSortHelper(nums, mid + 1, end);
inPlaceMerge(nums, start, end);
}

public void inPlaceMergeSort(int[] nums) {
inPlaceMergeSortHelper(nums, 0, nums.length - 1);
}
}``````

2. 关于本站的所有留言、评论、转载及引用，纯属内容发起人的个人观点，与本站观点和立场无关；
3. 关于本站的所有言论和文字，纯属内容发起人的个人观点，与本站观点和立场无关；
4. 本站文章均是网友提供，不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属；如您发现该文章侵犯了您的权益，可联系我们第一时间进行删除；
5. 本站为非盈利性的个人网站，所有内容不会用来进行牟利，也不会利用任何形式的广告来间接获益，纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。