數組簡單排序

簡單排序


冒泡排序

-----時間複雜度O(N2)

long[] a;
//數組中的數據項數
int nElems;
int out,in;
for(out = nElems-1; out > 1; out--){
    for(in = 0; in < out; in++){
        if(a[in] > a[in+1]){
            long temp = a[in];
            a[in] = a[in+1];
            a[in+1] = temp;
        }
    }
}

選擇排序

-----時間複雜度O(N2)

long[] a;
//數組中的數據項數
int nElems;
int out,in,min;
for(out = 0; out < nElems-1; out++){
    min = out;
    for (in = out+1;in<nElems;in++){
        if(a[in] < a[min]){
            min = in;
            long temp = a[min];
            a[min] = a[in];
            a[in] = temp;
        }
    }
}

插入排序

-----時間複雜度O(N2)

-----對於局部有序或基本有序數據運算只需要O(N),推薦使用

long[] a;
//數組中的數據項數
int nElems;
int in,out;
for (out = 1; out < nElems; out++){
    long temp = a[out];
    in = out;
    while (in > 0 && a[in-1] >= temp){
        a[in] = a[in-1];
        --in;
    }
    a[in] = temp;
}

a[in] = a[in-1];
–in;
}
a[in] = temp;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章