import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class z {
public static void main(String[] args) throws IOException {
// 文件绝对路径
FileReader fr = new FileReader(
"F:\\补丁\\作业\\largeW.txt");
BufferedReader br = new BufferedReader(fr);
List<String> list = new ArrayList<String>();
String rLine = "";
while ((rLine = br.readLine()) != null) {
list.add(rLine);
}
int number[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
number[i] = Integer.parseInt(list.get(i).trim());// 进行逐个转换,剔除空格
}
br.close();
long startTime = System.currentTimeMillis(); // 获取开始时间
// 归并排序
mergeSort(number);
long endTime = System.currentTimeMillis(); // 获取结束时间
//输出排序后的数据
for (int i = 0; i < list.size(); i++) {
System.out.println(number[i]);
}
System.out.print(list.size());
//将数组内数据写入TXT文件中
FileWriter fileWriter = new FileWriter(
"F:\\补丁\\作业\\largeW_merge.txt");
for (int i = 0; i < number.length; i++) {
fileWriter.write(String.valueOf(number[i]) + " ");
}
fileWriter.flush();
fileWriter.close();
System.out.println("归并排序运行时间: " + (endTime - startTime) + "ms");
}
public static void mergeSort(int[] data) {
sort(data, 0, data.length - 1);
}
public static void sort(int[] data, int left, int right) {
if (left >= right)
return;
// 找出中间索引
int center = (left + right) / 2;
// 对左边数组进行递归
sort(data, left, center);
// 对右边数组进行递归
sort(data, center + 1, right);
// 合并
merge(data, left, center, right);
//print(data);
}
public static void merge(int[] data, int left, int center, int right) {
// 临时数组
int[] tmpArr = new int[data.length];
// 右数组第一个元素索引
int mid = center + 1;
// third 记录临时数组的索引
int third = left;
// 缓存左数组第一个元素的索引
int tmp = left;
while (left <= center && mid <= right) {
// 从两个数组中取出最小的放入临时数组
if (data[left] <= data[mid]) {
tmpArr[third++] = data[left++];
} else {
tmpArr[third++] = data[mid++];
}
}
// 剩余部分依次放入临时数组
while (mid <= right) {
tmpArr[third++] = data[mid++];
}
while (left <= center) {
tmpArr[third++] = data[left++];
}
// (原left-right范围的内容被复制回原数组)
while (tmp <= right) {
data[tmp] = tmpArr[tmp++];
}
}
}
第三周作业——归并排序
最新推荐文章于 2024-10-23 20:49:45 发布