gpt4 book ai didi

java - 从哈希表中移动数据并对其进行排序

转载 作者:行者123 更新时间:2023-12-01 11:52:56 25 4
gpt4 key购买 nike

我正在编写一个程序来计算纯文本文件中单词出现的次数。为此,我使用哈希表。在获得所有单词以及它们出现的次数后,我想按字母顺序打印它们。为此,我需要从哈希表中取出对,然后根据每个单词在对数组中进行排序。我为此使用了合并排序:

/**
* Method to merge sort data pulled from a hash table
* Based on code found at: http://stackoverflow.com/questions/20795158/sorting-names-using-merge-sort
*
* @param names
* @return
*/
public static HashPair<String, Integer>[] mergeSort(HashPair<String, Integer>[] data)
{
HashPair<String, Integer>[] sortedData = null;
if (data.length >= 2) {
HashPair<String, Integer>[] left = new HashPair[data.length / 2];
HashPair<String, Integer>[] right = new HashPair[data.length - data.length / 2];

for (int i = 0; i < left.length; i++) {
if(data[i] != null)
{
left[i] = data[i];
}
}

for (int i = 0; i < right.length; i++) {
if(data[i + data.length / 2] != null)
{
right[i] = data[i + data.length / 2];
}
}

mergeSort(left);
mergeSort(right);
sortedData = merge(data, left, right);
}
return sortedData;
}

/**
* Helper method to merge the data back into one array
* Based on code found at: http://stackoverflow.com/questions/20795158/sorting-names-using-merge-sort
*
* @param names
* @param left
* @param right
*/
public static HashPair<String, Integer>[] merge(HashPair<String, Integer>[] data, HashPair<String, Integer>[] left, HashPair<String, Integer>[] right)
{
int a = 0;
int b = 0;
for (int i = 0; i < data.length; i++)
{
try
{
if (b >= right.length || (a < left.length && left[a].getFirst().compareToIgnoreCase(right[b].getFirst()) < 0))
{
data[i] = left[a];
a++;
}
else
{
data[i] = right[b];
b++;
}
}
catch(NullPointerException e)
{
continue;
}
}
return data;

这是我的主方法中调用排序并打印排序数据的代码

        HashPair<String, Integer>[] unsortedData = wordTable.getData(); //Getting unsorted data to be sorted
HashPair<String, Integer>[] sortedData = mergeSort(unsortedData);
System.out.printf("%-20s %-20s %-20s\n", "Index", "Key", "Value");
for(int i = 0; i < sortedData.length; i++)
{
if(sortedData[i] != null)
{
System.out.printf("%-20s %-20s %-20s\n", i, sortedData[i].getFirst(), sortedData[i].getSecond());
}
}

最后,我迭代排序数据并打印它的键和值,所有内容都打印得好像从未排序过,我不明白为什么。

最佳答案

我想你可以使用TreeMap来保持简单:

创建一个方法来添加到 TreeMap,例如:

private void addToTreeMap(TreeMap<String, Integer> tm, String str) {
if(tm.containsKey(str)) {
tm.put(str, tm.get(str).intValue() + 1);
}
else {
tm.put(str, 1);
}
}

现在使用这个方法:

TreeMap<String, Integer> tm = new TreeMap<String, Integer>();

addToTreeMap(tm, "bb");
addToTreeMap(tm, "aa");
addToTreeMap(tm, "aa");

要打印您可以执行的操作:

Set<String> setOfKeys = tm.keySet();
Iterator<String> iterator = setOfKeys.iterator();

while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("Word: "+key+", count: "+ tm.get(key));
key = null;
}

关于java - 从哈希表中移动数据并对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653486/

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