いくつかの簡単な並べ替え


もっと読む
泡の並べ替え
泡の並べ替えは,並べ替えアルゴリズムでは比較的簡単であるが,不変性の理解を助けることができる。
不変性とは、アルゴリズムにおいて、ある条件はアルゴリズム実行時に不変であり、常に本当であることを意味する。


/**
 *        out            ,       ,       .
 *       out       .
 */
    public void bubbleSort() {
        int out, in;
        for (out = nElements - 1; out >= 1; out--) { //   ,     
            for (in = 0; in < out; in++) { //   ,     
                if (array[in] > array[in+1]) { //    ,          .
                    long temp = array[in];
                    array[in] = array[in+1];
                    array[in+1] = temp;
                }
            }
        }
    }

並べ替えを選択
並べ替えを発泡体の秩序化と同様に、N*(N−1)/2回の比較、すなわちO(Nの二乗)とする。

/**
 *              out         ,       ,       .
 */
    public void selectionSort() {
        int out, in, min;
        long temp;
        for (out = 0; out < nElements; out++) {
            min = out; //    ,   .
            for (in = out + 1; in < nElements; in++) { //  in out+1     
                if (array[min] > array[in]) { //        
                    min = in; //          
                }
            }
            temp = array[out]; //           
            array[out] = array[min]; //               
            array[min] = temp;//               
        }
    }
並べ替えの挿入

/**
 *            out         ,    ,          ,           ,       ,       .
 */
public void insertionSort() {
        int out, in;
        for (out = 1; out < nElements; out++) { //out      , 1  .
            long temp = array[out]; //        
            in = out;
            while (in > 0 && array[in-1] > temp) { //while                    .
                array[in] = array[in-1];//       
                --in; //in      ,             
            }
            array[in] = temp; // in           
        }
    }