import java.util.Arrays;

public class Main {
public static void main(String[] args) {
int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
// 排序前:
  System.out.println(Arrays.toString(ns));
    for (int i = 0; i < ns.length - 1; i++) {
      for (int j = 0; j < ns.length - i - 1; j++) {
        if (ns[j] > ns[j+1]) {
          // 交换ns[j]和ns[j+1]:
          int tmp = ns[j];
          ns[j] = ns[j+1];
          ns[j+1] = tmp;
        }
       }
    }
// 排序后:
  System.out.println(Arrays.toString(ns));
  }
}

排序工作过程如下:

12 28 73 65 18 89 50 8 36 96
12 28 65 18 73 50 8 36 89
12 28 18 65 50 8 36 73
12 18 28 50 8 36 65
12 18 28 8 36 50
12 18 8 28 36
12 8 18 28
8 12 18
8 12

j<ns.length-i-1的原因是:每一轮循环后,最大的一个数被交换到末尾,因此,下一轮循环就可以“刨除”最后的数,每一轮循环都比上一轮循环的结束位置靠前一位。

 

Ps:Java的标准库已经内置了排序功能,我们只需要调用JDK提供的Arrays.sort()就可以排序:

  int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
  Arrays.sort(ns);
  System.out.println(Arrays.toString(ns));

posted on 2019-11-07 17:07  RGGL  阅读(143)  评论(0)    收藏  举报