平时积累一些好用的函数形成自己的函数库是个提高工作效率的好方法!
Java中运用数组的四种排序方法:
1.利用Arrays带有的排序方法快速排序
import java.util.Arrays; public class Test2{ public static void main(String[] args){ int[] a={5,4,2,4,9,1}; Arrays.sort(a); //进行排序 for(int i: a){ System.out.print(i); } } }2.冒泡法排序
public static int[] bubbleSort(int[] args){//冒泡排序算法 for(int i=0;i<args.length-1;i++){ for(int j=i+1;j<args.length;j++){ if (args[i]>args[j]){ int temp=args[i]; args[i]=args[j]; args[j]=temp; } } } return args; }
public static int[] selectSort(int[] args){//选择排序算法 for (int i=0;i<args.length-1 ;i++ ){ int min=i; for (int j=i+1;j<args.length ;j++ ){ if (args[min]>args[j]){ min=j; } } if (min!=i){ int temp=args[i]; args[i]=args[min]; args[min]=temp; } } return args; }
public static int[] insertSort(int[] args){//插入排序算法 for(int i=1;i<args.length;i++){ for(int j=i;j>0;j--){ if (args[j]<args[j-1]){ int temp=args[j-1]; args[j-1]=args[j]; args[j]=temp; }else break; } } return args; }
public class StreamTool { /** * 读取流数据 * @param inStream * @return */ public static String read(InputStream inStream) throws Exception{ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) != -1){ outputStream.write(buffer, 0, len); } inStream.close(); return new String(outputStream.toByteArray()); }
/** * 以行为单位读取文件,常用于读面向行的格式化文件 * * @param fileName * 待读文件 */ public static void testData(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 // System.out.println("line " + line + ": " + tempString); // 按照空格分隔字符串 String[] as = tempString.replaceAll("\\s{2,}", " ").split(" "); parseData(as); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } }
待积累....