本周的作业在第一冒泡排序出现问题,自己的电脑读取文件失败,后来在实验室试验成功,归并排序使用的方法是请教班里优秀的同学得到,现已经全部弄懂。
package zuoye_zhishu;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
public class Bubble {
public static void main(String[] args) {
ArrayList arraylist = new ArrayList();
try {
long time1, time2;
FileReader f = new FileReader("F:/test/largeW.txt");
BufferedReader br = new BufferedReader(f);
String line = br.readLine();
while (line != null) {
int nuqm = Integer.parseInt(line.trim());
arraylist.add(nuqm);
line = br.readLine();
}
int array1[] = new int[arraylist.size()];
int arrayNum[] = new int[arraylist.size()];
for(int i=0;i<array1.length;i++){
array1[i] = (Integer) arraylist.get(i);
}
String str;
time1 = System.currentTimeMillis();
mergeSort(array1,arrayNum, 0, array1.length-1);
time2 = System.currentTimeMillis();
System.out.println("归并排序时间:"+(time2-time1)/2);
FileWriter ww = new FileWriter(
"F:/test/largeW.txt");
BufferedWriter wMerge = new BufferedWriter(ww);
for (int i = 0; i < arrayNum.length; i++) {
System.out.println(arrayNum[i]);
str = String.valueOf(arrayNum[i]);
wMerge.write(str);
wMerge.newLine();
}
// bw.flush();
wMerge.flush();
wMerge.close();
// bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 冒泡排序
public static void BubbleSort(Object[] arr) {
int change;
for (int i = 1; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if ((Integer) arr[j] > (Integer) arr[j + 1]) {
change = (Integer) arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = change;
}
}
}
}
private static void mergeSort(int[] a, int[] tmp,int first, int last) {
if(first == last){
tmp[first] = a[first];
}
else{
int mid = (first + last) / 2;
mergeSort(a,tmp ,first, mid);
mergeSort(a,tmp, mid + 1, last);
merge(a,tmp, first, mid, last);
}
}//归并排序算法
private static void merge(int[]a, int[] tmp,int first, int mid, int last) {
int i = first;
int j = mid + 1;
int k = first;
// 逐个归并
while (i <= mid && j <= last) {
if ((Integer) a[i] <= (Integer) a[j])
tmp[k++] = (Integer) a[i++];
else
tmp[k++] = (Integer) a[j++];
}
// 将左边剩余的归并
while (i <= mid) {
tmp[k++] = (Integer) a[i++];
}
// 将右边剩余的归并
while (j <= last) {
tmp[k++] = (Integer) a[j++];
}
}
}
//运行结果较长,截图部分。