我在Merge Sorting算法中并行保存两个数组时遇到了麻烦。 假设我有数组defMergeSort和intMergeSort2。
我想按字典顺序排序String defMergeSort,
String[] defMergeSort = {"Echo", "Alpha", "Charlie", "Beta", "Alpha", "Echo"};
Array intMergeSort2表示与defMergeSort并行的元素位置。 (例如:defMergeSort [0] = Echo contingent to intMergeSort2 [0] = 0,defMergeSort [3] = Beta to intMergeSort2 [3] = 3) intMergeSort2将与defMergeSort并行重新排列,尽管未按数字排序,
int[] intMergeSort2 = {0,1,2,3,4,5};
最终结果应该与此类似(不确定我的示例中的intMergeSort2 []的并行排序是否对于defMergeSort []中的重复字符串是正确的:
以下合并排序算法可以按字典顺序排序defMergeSort,虽然我无法弄清楚如何保持defMergeSort并行如上所述:
//mergeSort code found at:
//http://www.buildingjavaprograms.com/code-files/2ed/ch13/MergeSort.java
public static void mergeSort(String[] defMergeSort, int[] intMergeSort2) {
if (defMergeSort.length > 1) {
// split array into two halves
String[] left = leftHalf(defMergeSort);
String[] right = rightHalf(defMergeSort);
// recursively sort the two halves
mergeSort(left, intMergeSort2);
mergeSort(right, intMergeSort2);
// merge the sorted halves into a sorted whole
merge(defMergeSort, intMergeSort2, left, right);
}
}
// Returns the first half of the given array.
public static String[] leftHalf(String[] defMergeSort) {
int size1 = defMergeSort.length / 2;
String[] left = new String[size1];
for (int i = 0; i < size1; i++) {
left[i] = defMergeSort[i];
}
return left;
}
// Returns the second half of the given array.
public static String[] rightHalf(String[] defMergeSort) {
int size1 = defMergeSort.length / 2;
int size2 = defMergeSort.length - size1;
String[] right = new String[size2];
for (int i = 0; i < size2; i++) {
right[i] = defMergeSort[i + size1];
}
return right;
}
// Merges the given left and right arrays into the given
// result array. Second, working version.
// pre : result is empty; left/right are sorted
// post: result contains result of merging sorted lists;
public static void merge(String[] defMergeSort, int[] intMergeSort2,
String[] left, String[] right){
int i1 = 0; // index into left array
int i2 = 0; // index into right array
for(int i = 0; i < defMergeSort.length; i++){
if (i2 >= right.length || (i1 < left.length &&
left[i1].compareTo(right[i2]) <= 0)) {
defMergeSort[i] = left[i1];
i1++;
} else {
defMergeSort[i] = right[i2];
i2++;
}
}
}
答案 0 :(得分:4)
定义一个包含整数和字符串值的对象,拥有该对象的单个数组,对该数组进行排序。
即。
class DataElement {
final String str;
final int i;
//Add constructor here
}
DataElement[] array; // sort this array
请注意,您需要在DataElement中实现Comparable
或为sort方法指定Comparator
以控制排序。
答案 1 :(得分:0)
我发现在你的情况下使用配对非常方便。确保包含。