第三周作业——冒泡排序和归并排序
2014-03-27 19:12
501 查看
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class bubble { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int t=0, flag = 10000; String line = null; List<Integer> list = new ArrayList<Integer>(); BufferedReader bReader = new BufferedReader(new FileReader("largeW.txt")); while((line=bReader.readLine())!=null && t<flag){ list.add(new Integer(line.trim())); t++; } bReader.close(); Integer[] data1 = new Integer[list.size()]; list.toArray(data1); long start = System.currentTimeMillis();//获取开始时间 bubbleSort(data1); long end = System.currentTimeMillis();//结束时间 System.out.println("冒泡排序的运行时间为:"+(end-start)+"ms"); Integer[] data2 = new Integer[list.size()]; list.toArray(data2); Integer[] d = new Integer[data2.length]; long b = System.currentTimeMillis();//获取开始时间 mergeSort(data2, d, 0, data2.length-1); long e = System.currentTimeMillis();//结束时间 System.out.print("归并排序的运行时间为:"+(e-b)+"ms"); FileWriter fw1 = new FileWriter(new File("merge.txt")); for(int i=0; i<d.length; i++){ fw1.write(d[i]+"\n"); } fw1.close(); FileWriter fw2 = new FileWriter(new File("bubble.txt")); for(int i=0; i<data1.length; i++){ fw2.write(data1[i]+"\n"); } fw2.close(); } public static Integer[] bubbleSort(Integer a[]){//冒泡排序 int temp; for(int j=0; j<a.length; j++){ for(int i=0; i<a.length-j-1; i++){ if(a[i] > a[i+1]){ temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } return a; } public static Integer[] mergeSort(Integer[] num, Integer[] num1, int s, int t) {//归并排序的递归算法 int m; Integer[] num2 = new Integer[t + 1]; if (s == t) num1[s] = num[s]; //待排序记录只有一个,递归结束 else { m = (s + t) / 2; mergeSort(num, num2, s, m);//左半部分递归调用 mergeSort(num, num2, m + 1, t);//右半部分递归调用 merg(num2, num1, s, m, t);//将两个已排序的子序列归并 } return num1; } public static void merg(Integer[] num, Integer[] num1, int l, int m, int n) {//一次归并算法 int i, j, k; i = l; j = m + 1; k = l; while (i <= m && j <= n) { if (num[i] < num[j]) num1[k++] = num[i++]; else { num1[k++] = num[j++]; } } while (i <= m) { num1[k++] = num[i++]; } while (j <= n) { num1[k++] = num[j++]; } } }
选取largeW.txt文件中的前10000条数据进行排序。。
运行结果:
相关文章推荐
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序(只完成冒泡算法)
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序(运行归并算法)
- 第三周作业——冒泡排序和归并排序
- 第三周作业-冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序
- 第三周作业——冒泡排序和归并排序(运行冒泡排序)
- 第三周作业——冒泡排序和归并排序