冒泡排序:
public static void main(String[] args) { int[] ns = { 1,3,59,165,1,3,61,65,165,1,5416,1,561,3,15,3,1 }; Hello hello = new Hello();//创建对象 hello.mpsortArr(ns);//调用排序方法 hello.toStringArr(ns);//调用输出 } //输出校验 public void toStringArr(int[] n) { for (int i = 0; i < n.length; i++) { System.out.print(n[i]+" "); } } //冒泡排序:将数组中的每一个前者与后者比较,若前者大则交换,一共比较n.length次。将上步骤循环n.length-1次,每一次都将最大的数放在最后,最终排序成功。 public void mpSortArr(int[] ns) { for (int i = 0; i < ns.length-1; i++) {//循环遍历数组,需要ns.length边遍历,每次遍历将最大的数放到最后 for (int j = 1; j < ns.length-i; j++) {//每次进行比较都比上一次比较的次数少1 if(ns[j]>ns[j-1]) {//比较两个相邻的数,较大的数往后排 int t = ns[j-1]; ns[j-1] = ns[j]; ns[j] = t; } } } }main方法中,args[]用来接收命令行参数(即JVM接收用户输入并传给main方法) 示例:
public class Main { public static void main(String[] args) { for (String arg : args) { if ("-version".equals(arg)) { System.out.println("v 1.0"); break; } } } }