0
マージソートと挿入の並べ替えを使用してファイルから文字列をソートしようとしています。私は並べ替えの部分を行ったが、私はすべての重複した単語を削除する必要がある部分に立ち往生している。簡単に言えば、重複した単語を削除しながらファイルから文字列をソートするには、マージと挿入の並べ替えから実行までの実行時間を印刷する必要があります。文字列ファイルから重複する単語を削除する
FRANKENSTEIN
MARY
ウルストンクラフト
SHELLEY
LETTER
TO 10
これはtxtファイルの外観ですが、その中に15,000以上の単語が含まれています。重複した単語を削除してからソートする必要がある部分を見つけ出すことはできません。事前
ergeSort pb = new ergeSort();
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
List<String> l = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
l.add(line);
}
br.close();
String[] arre = l.toArray(new String[]{});
startTime = System.currentTimeMillis();
(new ergeSort()).MergeSort(arre);
removeDuplicate(arre);
for(String h : arre){
System.out.println(h);
}
endTime = System.currentTimeMillis();
long executionTime1 = endTime - startTime;
startTime = System.currentTimeMillis();
inSort(arre);
removeDuplicate(arre);
endTime = System.currentTimeMillis();
long executionTime2 = endTime - startTime;
System.out.println("The execution time of Merge sort after duplicated words are removed is: " + executionTime1 + "ms");
System.out.println("The execution time of Insertion sort after duplicated words are removed is: " + executionTime2 + " ms");
System.out.println("The number of words remaining after removal of duplicated: " + arre.length);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Incorrect File");
}
}
public static class ergeSort {
public static void MergeSort(String[] arr) {
if (arr.length > 1) {
String[] firstHalf = new String[arr.length/2];
System.arraycopy(arr, 0, firstHalf, 0, arr.length/2);
MergeSort(firstHalf);
String[] secondHalf = new String[arr.length - arr.length/2];
System.arraycopy(arr, arr.length/2, secondHalf, 0, arr.length - arr.length/2);
MergeSort(secondHalf);
merge(firstHalf, secondHalf, arr);
}
}
public static void merge(String[] arr1, String[] arr2, String[] temp) {
int a = 0;
int b = 0;
for (int i = 0; i < temp.length; i++) {
if (b >= arr2.length || (a < arr1.length && arr1[a].compareToIgnoreCase(arr2[b]) < 0)) {
temp[i] = arr1[a];
a++;
} else {
temp[i] = arr2[b];
b++;
}
}
}
}
public static String[] inSort(Comparable[] arr) {
Comparable temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j > 0; j--) {
if (arr[j].compareTo(arr[j - 1]) < 0) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
return (String[]) arr;
}
public static void removeDuplicate(String[] words) {
{
List<String> q = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (words[i] != null) {
for (int j = i + 1; j < words.length; j++) //Inner loop for Comparison
{
if (words[i].compareToIgnoreCase(words[j])) //Checking for both strings are equal
{
q.add(words[i]);
}
}
}
}
}
}
}で
おかげで
なぜTreeSetを使用しないのですか? http://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html – IddoE
何らかの 'Set'を使用してファイルを読み込んで保存し、重複を削除することが保証されています – MadProgrammer