gpt4 book ai didi

java - 错误地合并排序输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:40 24 4
gpt4 key购买 nike

合并排序。

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithms;

import java.util.Arrays;

/**
*
* @author Navin
*/
public class MergeSort {

int [] left;
int [] right;

public void Merge_Sort(int [] array){
if(array.length<2){
return;
}

int mid = array.length/2;
left = new int[mid];
right = new int[array.length-mid];

for(int i =0;i<mid;i++){
left[i] = array[i];
}

for(int j =mid;j<array.length;j++){
right[j-mid] = array[j];

}

System.out.println(Arrays.toString(left));
System.out.println(Arrays.toString(right));

Merge_Sort(left);
Merge_Sort(right);
Merge(left,right,array);
}


public void Merge(int [] left, int [] right, int [] array){

int i=0;
int j=0;
int k=0;

while(i<left.length && j<right.length){

if(left[i] < right[j]){
array[k] = left[i];
i++;
}else{
array[k] = right[j];
j++;
}
k++;
}

}

public static void main(String[] args) {
int [] array = {2,4,1,6,8,5,3,7};
MergeSort ms = new MergeSort();

ms.Merge_Sort(array);
System.out.println(Arrays.toString(array));
}
}

我不确定上面有什么问题,逻辑和实现是正确的,但输出是一个未排序的数组,与输入相同。

输出: [2, 4, 1, 6, 8, 5, 3, 7]

最佳答案

我测试了你的代码,你的合并方法是错误的。使用此代码,一切都应该没问题:

public void merge(int[] left, int[] right, int[] array) {
int i = 0, j = 0, k = 0;

while (i < left.length && j < right.length) {
if (left[i] < right[j])
array[k++] = left[i++];
else
array[k++] = right[j++];
}

while (i < left.length)
array[k++] = left[i++];

while (j < right.length)
array[k++] = right[j++];

return;
}

阅读this great SO post有关如何在 Java 中合并两个排序数组的信息。

关于java - 错误地合并排序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34390262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com