第2次实验--算法基本功与综合思考

对文件 largeW.txt下载链接中的数据,应用快速排序算法进行排序,并与冒泡排序、归并排序进行时间比较。体验算法复杂度对设计算法的影响。


比较算法:冒泡排序、归并排序(之前博客已测试)

类说明:

1.ReadFile - 读取文件数据

2.WriteFile - 数据写入文件

3.QuickSort - 快速排序实现

4.Main - 测试类



代码如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile
{
	public int[] readArray(String filePath) throws FileNotFoundException
	{
		int count = 0;
		Scanner scan = new Scanner(new File(filePath));
		
		while (scan.hasNextInt())
		{
			count++;
			scan.nextInt();
		}
		
		int[] array = new int[count];

		scan = new Scanner(new File(filePath));
		int index = 0;
		
		while (scan.hasNextInt())
		{
			array[index] = scan.nextInt();
			index++;
		}
		
		scan.close();
		return array;
	}
}

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class WriteFile
{
	public void writeToFile(int[] array, String fileName)
			throws FileNotFoundException
	{

		PrintWriter pw = new PrintWriter(new File(fileName));
		
		for (int i = 0, lineCount = array.length; i < lineCount; i++)
		{
			pw.println(array[i]);
		}
		
		pw.close();
	}
}

public class QuickSort
{
	public int once(int[] array, int start, int end)
	{
		int i = start, j = end, temp = 0;
		
		while (i < j)
		{
			while (i < j && array[i] <= array[j])
				j--;

			if (i < j)
			{
				temp = array[i];
				array[i] = array[j];
				array[j] = temp;
				i++;
			}
			while (i < j && array[i] <= array[j])
				i++;
			
			if (i < j)
			{
				temp = array[i];
				array[i] = array[j];
				array[j] = temp;
				j--;
			}
		}
		
		return i;// 返回记录的位置
	}

	public void quickSort(int[] array, int start, int end)
	{
		if (start < end)
		{
			int location = once(array, start, end);
			quickSort(array, start, location - 1);
			quickSort(array, location + 1, end);
		}
	}
}

import java.io.FileNotFoundException;

import QuickSort;
import ReadFile;
import WriteFile;

public class Main
{
	public static void main(String[] args)
	{
		ReadFile rf = new ReadFile();
		
		try
		{
			int[] array = rf.readArray("largeW.txt");

			QuickSort qs = new QuickSort();
			
			long startTime = System.currentTimeMillis();
			qs.quickSort(array, 0, array.length - 1);
			long endTime = System.currentTimeMillis();
			
			System.out.println("快速排序使用时长:" + (endTime - startTime) + "ms");

			WriteFile wf = new WriteFile();
			wf.writeToFile(array, "txt/sorted.txt");

		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
}

运行时间:163ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值