选择排序简单理解

选择排序

public class Test {
   public static void main(String[] args) {
       int[] a={1,5,6,723,21,23,4,5,6};
       sort(a);
       for (int i : a) {
           System.out.print("-"+i);
       }
   }
   public static int[] sort(int[] a){

       for (int i = 0; i < a.length; i++) {
           int k=i;
           for (int j = i+1;j < a.length; j++){
               if(a[j]<a[k]){
                   k=j;
               }
           }
           int temp=a[i];
           a[i] = a[k];
           a[k] = temp;
           for (int i1 : a) {
               System.out.print("-"+i1+"-");
           }
           System.out.println("");
       }
       return a;
   }
}

算法过程如下:

  1. -1–5--6–723–21–23–4--5–6-
  2. -1–4--6–723–21–23–5--5–6-
  3. -1–4--5–723–21–23–6--5–6-
  4. -1–4--5–5--21–23–6--723–6-
  5. -1–4--5–5--6–23–21–723–6-
  6. -1–4--5–5--6–6--21–723–23-
  7. -1–4--5–5--6–6--21–723–23-
  8. -1–4--5–5--6–6--21–23–723-
  9. -1–4--5–5--6–6--21–23–723-
    结果: -1-4-5-5-6-6-21-23-723

从第一个数开始,往后找到最小的数与之交换位置;接着从第二个数开始,往后找到最小的数与之交换位置;直到最后一个数,选择排序完成。

上一篇:neutron网络实践


下一篇:CSS元素显示模式 - 723