簡單排序
冒泡排序
-----時間複雜度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;
}