package com.worthtech.app.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import javax.servlet.http.HttpServletRequest; public class Util { public static String error = ""; public static String lastKey = ""; public static String tel = ""; private static MessageDigest digest = null; public String hash(String data) {//MD5加密 if (digest == null) try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. We will be unable to function normally."); nsae.printStackTrace(); } digest.update(data.getBytes()); return encodeHex(digest.digest()); } public String encodeHex(byte bytes[]) { StringBuffer buf = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { if ((bytes[i] & 0xff) < 16) buf.append("0"); buf.append(Long.toString(bytes[i] & 0xff, 16)); } return buf.toString().toUpperCase(); } public static String getCurrentDate(){ Calendar day=Calendar.getInstance(); day.add(Calendar.DATE,0); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String date1 = sdf.format(day.getTime()); return date1; } public static String getCurrentDate(String format){ Calendar day=Calendar.getInstance(); day.add(Calendar.DATE,0); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(day.getTime()); return date; } public static String getYesterdayDate(String format){ Calendar day=Calendar.getInstance(); day.add(Calendar.DATE,-1); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(day.getTime()); return date; } /** * @param date1 需要比较的时间 不能为空(null),需要正确的日期格式 ,如:2009-09-12 * @param date2 被比较的时间 为空(null)则为当前时间 * @param stype 返回值类型 0为多少天,1为多少个月,2为多少年 * @return * 举例: * compareDate("2009-09-12", null, 0);//比较天 * compareDate("2009-09-12", null, 1);//比较月 * compareDate("2009-09-12", null, 2);//比较年 */ public static int compareDate(String startDay,String endDay,int stype){ int n = 0; String[] u = {"天","月","年"}; String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd"; endDay = endDay==null?getCurrentDate("yyyy-MM-dd"):endDay; DateFormat df = new SimpleDateFormat(formatStyle); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); try { c1.setTime(df.parse(startDay)); c2.setTime(df.parse(endDay)); } catch (Exception e3) { System.out.println("wrong occured"); } //List list = new ArrayList(); while (!c1.after(c2)) { // 循环对比,直到相等,n 就是所要的结果 //list.add(df.format(c1.getTime())); // 这里可以把间隔的日期存到数组中 打印出来 n++; if(stype==1){ c1.add(Calendar.MONTH, 1); // 比较月份,月份+1 } else{ c1.add(Calendar.DATE, 1); // 比较天数,日期+1 } } n = n-1; if(stype==2){ n = (int)n/365; } // System.out.println(startDay+" -- "+endDay+" 相差多少"+u[stype]+":"+n); return n; } //////////////////////////////////////////////////// public static String genNumPassword(int length) { if (length < 1) return null; String strChars[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; StringBuffer strPassword = new StringBuffer(); int nRand = (int) Math.round(Math.random() * 100D); for (int i = 0; i < length; i++) { nRand = (int) Math.round(Math.random() * 100D); strPassword.append(strChars[nRand % (strChars.length - 1)]); } return strPassword.toString(); } public static String getPrefixLine(int level, String txt) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < level * 2; i++) { sb.append(txt); } return sb.toString(); } public static String getActionMappingURL(String action,HttpServletRequest request) { StringBuffer value = new StringBuffer(request.getContextPath()); // Use our servlet mapping, if one is specified String servletMapping = "*.portal"; if (servletMapping != null) { String queryString = null; int question = action.indexOf("?"); if (question >= 0) { queryString = action.substring(question); } String actionMapping = getActionMappingName(action); if (servletMapping.startsWith("*.")) { value.append(actionMapping); value.append(servletMapping.substring(1)); } else if (servletMapping.endsWith("/*")) { value.append(servletMapping.substring(0, servletMapping.length() - 2)); value.append(actionMapping); } else if (servletMapping.equals("/")) { value.append(actionMapping); } if (queryString != null) { value.append(queryString); } }else { if (!action.startsWith("/")) { value.append("/"); } value.append(action); } return (value.toString()); } public static String getActionMappingName(String action) { String value = action; int question = action.indexOf("?"); if (question >= 0) { value = value.substring(0, question); } int slash = value.lastIndexOf("/"); int period = value.lastIndexOf("."); if ((period >= 0) && (period > slash)) { value = value.substring(0, period); } if (value.startsWith("/")) { return (value); } else { return ("/" + value); } } public static String FormatSum(String sum){//00000012345->123.45 if(sum==null||sum.length()<2){ return "0.00"; } String decimal = "." + sum.substring(sum.length()-2, sum.length()); String integer = killZero(sum.substring(0, sum.length()-2)); integer += decimal; return integer; } public static String killZero(String sum){//00001234500->1234500 String temp = ""; for(int i = 0 ;i<sum.length();i++){ if(sum.charAt(i) != '0' || i == sum.length()-1){ temp = sum.substring(i,sum.length()); break; } } return temp; } public static String getTranamt(String str) { String tmp = ""; if(str.equals("-")){ return str; } char c[] = str.toCharArray(); if (str.length() != 1) { for (int i = 0; i < c.length; i++) { if (!String.valueOf(c[i]).equals("0")) { tmp = str.substring(i, str.length()); break; } } } else { tmp = str; } StringBuffer sb = new StringBuffer(); sb.append(tmp); if (sb.length() > 2) { sb.insert(sb.length() - 2, "."); } if (sb.length() == 2) { sb.insert(0, "0."); } if (sb.length() == 1) { sb.insert(0, "0.0"); } return sb.toString(); } public static String numtochinese(String input) { String s1 = "零壹贰叁肆伍陆柒捌玖"; String s4 = "分角整元拾佰仟万拾佰仟亿拾佰仟"; String temp = ""; String result = ""; if (input == null) return "输入字串不是数字串只能包括以下字符(′0′~′9′,′.′),输入字串最大只能精确到仟亿,小数点只能两位!"; temp = input.trim(); float f; try { f = Float.parseFloat(temp); } catch (Exception e) { return "输入字串不是数字串只能包括以下字符(′0′~′9′,′.′),输入字串最大只能精确到仟亿,小数点只能两位!"; } int len = 0; if (temp.indexOf(".") == -1) len = temp.length(); else len = temp.indexOf("."); if (len > s4.length() - 3) return ("输入字串最大只能精确到仟亿,小数点只能两位!"); int n1, n2 = 0; String num = ""; String unit = ""; for (int i = 0; i < temp.length(); i++) { if (i > len + 2) { break; } if (i == len) { continue; } n1 = Integer.parseInt(String.valueOf(temp.charAt(i))); num = s1.substring(n1, n1 + 1); n1 = len - i + 2; unit = s4.substring(n1, n1 + 1); result = result.concat(num).concat(unit); } if ((len == temp.length()) || (len == temp.length() - 1)) result = result.concat("整"); if (len == temp.length() - 2) result = result.concat("零分"); return result; } //左补0 public static String addZero(String str, int destLen){ String temp = str; if(temp == null){ System.out.println("null in AddZero"); temp = ""; } if(temp.length() >= destLen){ return temp.substring(temp.length()-destLen, temp.length()); } while(temp.length() < destLen){ temp = "0" + temp; } return temp; } public static String getNewString(String old,int num){ String tmp = ""; if(old==null){ old = ""; } old = old.replace(" ", ""); if(old.getBytes().length<=num){ for(int i = old.getBytes().length;i<num;i++){ tmp += " "; } old = old + tmp; }else{ old = old.substring(0,num); } return old; } //右补0,直到满12位 public static String getAMT(String old){ if(old==null){ old = ""; } String tmp = ""; for(int i = old.length();i<12;i++){ tmp += "0"; } old = tmp+old; return old; } public static String getFormatString(String s){//去“-” StringBuffer sb=new StringBuffer(); char[] c=s.toCharArray(); for(int i=0;i<c.length;i++){ if(c[i]=='-'){ }else{ sb.append(c[i]); } } return sb.toString(); } public static String anti_getFormatString(String s){//20090909->2009-09-09 if(s==null||s.length()<8){ return ""; } return s.substring(0,4)+"-"+s.substring(4,6)+"-"+s.substring(6); } public static String moneyFormat(String money,int length){//123.45->00000012345 if(money==null||money.equals("")){ return ""; } int iTemp = money.indexOf("."); String sTemp=""; if (iTemp == -1) { sTemp = money + "00"; } else if (iTemp + 2 == money.length()) { sTemp = money.substring(0, iTemp) + money.charAt(iTemp + 1) + "0"; } else { sTemp = money.substring(0, iTemp) + money.substring(iTemp + 1, iTemp + 3); } return Util.addZero(sTemp, length); } public static String moneyFormat2(String money){//23->23.00 StringBuffer sb=new StringBuffer(); if(money==null){ return "0.00"; } int index=money.indexOf("."); if(index==-1){ return money+".00"; }else{ String s0=money.substring(0,index);//整数部分 String s1=money.substring(index+1);//小数部分 if(s1.length()==1){//小数点后一位 s1=s1+"0"; }else if(s1.length()>2){//如果超过3位小数,截取2位就可以了 s1=s1.substring(0,2); } sb.append(s0); sb.append("."); sb.append(s1); } return sb.toString(); } /** * 在list中查询以prefix开头的子项,返回符合匹配的list * @param list * @param prefix * @return */ public static List findMatches(List list,String prefix) { String prefix_upper = prefix.toUpperCase(); List matches = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { String name = (String) iter.next(); String name_upper = name.toUpperCase(); if (name_upper.startsWith(prefix_upper)) { matches.add(name); } } return matches; } /** * 统计字符出现次数 * @param s */ public static void statistics(String s) { Map<Character, Integer> map = new HashMap<Character, Integer>(); int i, size = s.length(); for (i = 0; i < size; i++) { char c = s.charAt(i); map.put(c, map.containsKey(c) ? ((Integer) map.get(c) + 1) : 1); } // System.out.println(map); } // 生成不重复随机数1 /** * 根据给定的最小数字和最大数字,以及随机数的个数,产生指定的不重复的数组 * @param begin 最小数字(包含该数) * @param end 最大数字(不包含该数) * @param size 指定产生随机数的个数 */ public static int[] generateRandomNumber(int begin, int end, int size) { // 加入逻辑判断,确保begin<end并且size不能大于该表示范围 if (begin >= end || (end - begin) < size) { return null; } // 种子你可以随意生成,但不能重复 int[] seed = new int[end - begin]; for (int i = begin; i < end; i ++) { seed[i - begin] = i; } int[] ranArr = new int[size]; Random ran = new Random(); // 数量你可以自己定义。 for (int i = 0; i < size; i++) { // 得到一个位置 int j = ran.nextInt(seed.length - i); // 得到那个位置的数值 ranArr[i] = seed[j]; // 将最后一个未用的数字放到这里 seed[j] = seed[seed.length - 1 - i]; } return ranArr; } // 生成不重复随机数2 /** * 根据给定的最小数字和最大数字,以及随机数的个数,产生指定的不重复的数组 * @param begin 最小数字(包含该数) * @param end 最大数字(不包含该数) * @param size 指定产生随机数的个数 */ public static Integer[] generateBySet(int begin, int end, int size) { // 加入逻辑判断,确保begin<end并且size不能大于该表示范围 if (begin >= end || (end - begin) < size) { return null; } Random ran = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size() < size) { set.add(begin + ran.nextInt(end - begin)); } Integer[] ranArr = new Integer[size]; ranArr = set.toArray(new Integer[size]); //ranArr = (Integer[]) set.toArray(); return ranArr; } public static String toUTF(String iso){ if(iso==null){ return null; } String data=""; try { data = new String(iso.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data; } public static String toChinese(String chinese){ if(chinese==null){ return null; } String data=""; try { data=java.net.URLDecoder.decode(chinese,"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data; } // 判断时间是否符合时间格式 public static boolean isDate(String date, String dateFormat) { if (date != null) { java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(dateFormat); format.setLenient(false); try { format.format(format.parse(date)); } catch (ParseException e) { // TODO Auto-generated catch block return false; } return true; } return false; } /** * 实现给定某日期,判断是星期几 * date:必须yyyy-MM-dd格式 */ public static String getWeekday(String date){ SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdw = new SimpleDateFormat("E"); Date d = null; try { d = sd.parse(date); } catch (ParseException e) { e.printStackTrace(); } return sdw.format(d); } // 用来全局控制 上一周,本周,下一周的周数变化 private static int weeks = 0; // 获得当前日期与本周一相差的天数 private static int getMondayPlus() { Calendar cd = Calendar.getInstance(); // 获得今天是一周的第几天,星期日是第一天,星期二是第二天...... int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { return -6; } else { return 2 - dayOfWeek; } } // 获得本周星期一的日期 public static String getCurrentMonday(String format) { weeks = 0; int mondayPlus = getMondayPlus(); Calendar currentDate=Calendar.getInstance(); currentDate.add(Calendar.DATE, mondayPlus); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(currentDate.getTime()); return date; } // 获得上周星期一的日期 public static String getPreviousMonday(String format) { weeks--; int mondayPlus = getMondayPlus(); Calendar currentDate=Calendar.getInstance(); currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(currentDate.getTime()); return date; } // 获得下周星期一的日期 public static String getNextMonday(String format) { weeks++; int mondayPlus = getMondayPlus(); // GregorianCalendar currentDate = new GregorianCalendar(); Calendar currentDate=Calendar.getInstance(); currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(currentDate.getTime()); return date; } // 获得相应周的周日的日期 public static String getSunday(String format) { int mondayPlus = getMondayPlus(); Calendar currentDate=Calendar.getInstance(); currentDate.add(Calendar.DATE, mondayPlus + 7 * weeks + 6); SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd" String date = sdf.format(currentDate.getTime()); return date; } //判断String是否是整数 public static boolean isInteger(String s){ if((s != null)&&(s!="")) return s.matches("^[0-9]*$"); else return false; } /** * 判断字符串是否是浮点数 */ public static boolean isDouble(String value) { try { Double.parseDouble(value); if (value.contains(".")) return true; return false; } catch (NumberFormatException e) { return false; } } /** * 判断字符串是否是数字 */ public static boolean isNumber(String value) { return isInteger(value) || isDouble(value); } public static void main(String[] args){ // System.out.println(new Util().hash("111111")); // Util util=new Util(); // if(util.isDate("20090817", "yyyyMMdd")){ // System.out.println("yes"); // }else{ // System.out.println("no"); // } // statistics("adfsfsadfsadfsadfasdf"); // int[] ranArr = generateRandomNumber(1,35,7); // System.out.println(Arrays.toString(ranArr)); // System.out.println("numtochinese="+numtochinese("1234567890")); } }
/** * 在第一个字符串中查找匹配字符串的个数 * @param str * @param regexStr * @return */ public static int count(String str,String regexStr){ int count = 0; Pattern pt = Pattern.compile(regexStr); Matcher m = pt.matcher(str); int start = 0; while(m.find()){ count++; } return count; } /** * 根据正则表达式分割str字符串成为一个一个的小的单元! * (实际使用:在一个类似语法分析的模块中发挥重要作用) * 例如:3+5*4 根据正则表达式+-\* 分割成数组 3,+,5,*,4 * @param str * @param regexStr * @return */ public static List splitByStr(String str,String regexStr){ List temp = new ArrayList(); Pattern pt = Pattern.compile(regexStr); Matcher m = pt.matcher(str); int start = 0; while(m.find()){ //去掉下面的字符串中为空串的情况! if(m.start()!=start) temp.add(str.substring(start, m.start())); temp.add(str.substring(m.start(),m.end())); start = m.end(); } temp.add(str.substring(start)); return temp; } /** * 检查是否含有指定的正则表达式匹配的子串. * @param str 目标字符串 * @param regex 正则表达式,如果正则表达式含有"^......$"就是查找整个字符串对象是否符合正则表达式. * @return */ public static boolean checkInclude(String str,String regex){ Pattern pattern = Pattern.compile(regex); Matcher matcher = null; matcher = pattern.matcher(str); return matcher.find(); } /** * 方法字符串中符合正则表达式的子串的集合. * @param str * @param regex * @return */ public static List getRightSubStr(String str, String regex) { List ans = new ArrayList(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); while (matcher.find()) { //注意要下面的goup()函数中可以含有数字,表示查找得到正则表达式中的goup匹配串. ans.add(matcher.group()); System.out.println("找到匹配的字符串 \"" + matcher.group() + "\" 开始于 " + matcher.start() + " 结束于 " + matcher.end() + "."); } return ans; }
/** * 超大整数相加: * 题目要求:如果系统要使用超大整数(超过long的范围),请你设计一个数据结构来存储这种 * 超大型数字以及设计一种算法来实现超大整数的加法运算 * @author Administrator * */ public class VeryBigNumAdd { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* String a="1223232"; for(int i=a.length()-1;i>=0;i--) { System.out.print(a.charAt(i)); } */ VeryBigNumAdd vbn=new VeryBigNumAdd(); String a="123453243455535634535252345234677576252241234123523453664563634"; String b="123453243455535634535252345234677576252241234123523453664563634"; String result=vbn.doAdd(a,b); System.out.println("result:"+result); } /** * * @param a 加数字符串1 * @param b 加数字符串2 * @return 结果字符串 * 分析: * 1、取得两个字符串的长度 * 2、把两个的长度做比较,并得出较长的长度,及较短的长度 * 3、把长度较短的加数字符串,在左面补0,使之与较长的字符串一样长 * 4、从最高位,一个个数的取出来相加,当然首先得转换为整型 * 5、设置进位,如果两个数相加及加上进位大于等于10,并且这不是最左边一个字符相加,相加结果等于 * (取出1+取出2+进位)-10,并把进位设为1;如果没有大于10,就把进位设为0,如些循环,把 * 相加的结果以字符串的形式结合起来,就得到最后的结果 */ String doAdd(String a,String b) { String str=""; int lenA=a.length(); int lenB=b.length(); int maxLen=(lenA>lenB) ? lenA : lenB; int minLen=(lenA<lenB) ? lenA : lenB; String strTmp=""; for(int i=maxLen-minLen;i>0;i--) { strTmp+="0"; } //把长度调整到相同 if(maxLen==lenA) { b=strTmp+b; }else a=strTmp+a; int JW=0;//进位 for(int i=maxLen-1;i>=0;i--) { int tempA=Integer.parseInt(String.valueOf(a.charAt(i))); int tempB=Integer.parseInt(String.valueOf(b.charAt(i))); int temp; if(tempA+tempB+JW>=10 && i!=0) { temp=tempA+tempB+JW-10; JW=1; } else { temp=tempA+tempB+JW; JW=0; } str=String.valueOf(temp)+str; } return str; } }
1.写一个方法,用一个for循环打印九九乘法表 /** *//** * 打印九九乘法口诀表 */ public void nineNineMulitTable(){ for (int i = 1,j = 1; j <= 9; i++) { System.out.print(i+"*"+j+"="+i*j+" "); if(i==j){ i=0; j++; System.out.println(); } } } 2.给定一个java.util.Date对象,如何转化为”2007-3-22 20:23:22”格式的字符串 /** *//** * 将某个日期以固定格式转化成字符串 * @param date * @return str */ public String date2FormatStr(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = sdf.format(date); return str; } 3.写一个方法,能够判断任意一个整数是否素数 /** *//** * 判断任意一个整数是否素数 * @param num * @return boolean */ public boolean isPrimeNumber(int num) { for (int i = 2; i <= Math.sqrt(num); i++) { if(num%i==0) { return false; } } return true; } 4.写一个方法,输入任意一个整数,返回它的阶乘 /** *//** *获得任意一个整数的阶乘 *@param n *@returnn! */ public int factorial(int num) { //递归 if(num == 1) { return 1; } return num*factorial(num-1); } 5.写一个方法,用二分查找法判断任意整数在任意整数数组里面是否存在,若存在就返回它在数组中的索引位置,不存在返回-1 /** *//** *二分查找特定整数在整型数组中的位置(递归) *@param dataset *@param data *@param beginIndex *@param endIndex *@return index */ public int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){ int midIndex = (beginIndex+endIndex)/2; //如果查找的数要比开始索引的数据要小或者是比结束索引的书要大,或者开始查找的索引值大于结束的索引值返回-1没有查到 if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ return -1; } if(data <dataset[midIndex]){ return binarySearch(dataset,data,beginIndex,midIndex-1); }else if(data>dataset[midIndex]) { return binarySearch(dataset,data,midIndex+1,endIndex); }else { return midIndex; } } /** *//** *二分查找特定整数在整型数组中的位置(非递归) *@param dataset *@param data *@return index */ public int binarySearch(int[] dataset ,int data) { int beginIndex = 0; int endIndex = dataset.length - 1; int midIndex = -1; if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ return -1; } while(beginIndex <= endIndex) { midIndex = (beginIndex+endIndex)/2; if(data <dataset[midIndex]) { endIndex = midIndex-1; } else if(data>dataset[midIndex]) { beginIndex = midIndex+1; }else { return midIndex; } } return -1; } 一,冒泡排序: package com.sort; import java.util.Random; public class No1Maopao { public static void main(String[] args) { Random rd = new Random(); //生成随即数组 int [] src = new int[10]; for(int i=0;i<10;i++){ src[i]=rd.nextInt(100); } //排序前打印数组所有元素 for(int i:src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); src = sort(src); //排序后打印数组所有元素 for(int i:src) System.out.println(i); } public static int[] sort(int [] src){ for (int i = 0; i < src.length; i++) { for(int j=i;j<src.length;j++){ if(src[j]<src[i]){ int temp = src[j]; src[j]=src[i]; src[i]=temp; } } } return src; } } 二、选择排序: package com.sort; import java.util.Random; public class No2XuanZhe { public static void main(String[] args) { Random rd = new Random(); int[] src = new int[10]; for (int i = 0; i < 10; i++) { src[i] = rd.nextInt(100); } for (int i : src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); src = sort(src); for (int i : src) System.out.println(i); } public static int[] sort(int[] src) { int min; for (int i = 0; i < src.length; i++) { min = src[i]; for (int j = i + 1; j < src.length; j++) { if (src[j] < min) { min = src[j]; int temp = src[i]; src[i] = src[j]; src[j] = temp; } } } return src; } } 三、插入排序: package com.sort; import java.util.Random; public class No3ChaRu { public static void main(String[] args) { Random rd = new Random(); int[] src = new int[10]; for (int i = 0; i < 10; i++) { src[i] = rd.nextInt(100); } for (int i : src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); src = sort(src); for (int i : src) System.out.println(i); } public static int[] sort(int[] src) { int in, out; for (in = 1; in < src.length; in++) { int temp = src[in]; out = in; while (out > 0 && src[out - 1] >= temp) { src[out] = src[out - 1]; --out; } src[out] = temp; } return src; } } 四、希尔排序: package com.sort; import java.util.Random; public class No4Xier { public static void main(String[] args) { Random rd = new Random(); int[] src = new int[10]; for (int i = 0; i < 10; i++) { src[i] = rd.nextInt(100); } for (int i : src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); src = sort(src); for (int i : src) System.out.println(i); } public static int[] sort(int[] src) { int len = src.length; int temp, i, j; int h = 1; while (h <= len / 3) h = h * 3 + 1; while (h > 0) { for (i = h; i < len; i++) { temp = src[i]; j = i; while (j > h - 1 && src[j - h] >= temp) { src[j] = src[j - h]; j -= h; } src[j] = temp; } h = (h - 1) / 3; } return src; } } 五、快速排序: public class No5Kuaisu { public static void quickSort(int[] array) { quickSort(array, 0, array.length - 1); } private static void quickSort(int[] array, int low, int high) { if (low < high) { int p = partition(array, low, high); quickSort(array, low, p - 1); quickSort(array, p + 1, high); } } private static int partition(int[] array, int low, int high) { int s = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (array[j] < s) { i++; swap(array, i, j); } } swap(array, ++i, high); return i; } private static void swap(int[] array, int i, int j) { int temp; temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void main(String[] args) { Random rd = new Random(); int[] src = new int[10]; for (int i = 0; i < 10; i++) { src[i] = rd.nextInt(100); } for (int i : src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); quickSort(src); for (int i : src) System.out.println(i); System.out.println("---------------可爱的分割线-------------------"); } }