最近有空,写了常见的几种排序算法的C++实现,包括改进版本的冒泡排序,简单选择排序,直接插入排序,快速排序,堆排序。
1 改进版本的冒泡排序:
//改进版本的冒泡排序;
void swapData(vector<int>& L,int i,int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
void sortData(vector<int>& L,int length)
{
int i,j;
bool flag = true;
for (i=0;i<length&&flag;++i){
flag = false;
for (j=length-2;j>i;--j){
if (L[j+1] < L[j]){
swapData(L,j+1,j);
flag = true;
}
}
}
}
int main()
{
vector<int> L = {1,3,6,8,4,6,99,77};
int length = L.size();
sortData(L,length);
for (int i=0;i<length;++i)
cout<<L[i]<<endl;
}
2 简单选择排序:
//简单选择排序;
void swapData(vector<int>& L,int i,int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
void selectSort(vector<int>& L,int length)
{
int i,j,minValue;
for (i=0;i<length;++i){
minValue = i;
for (j=i+1;j<length;++j){
if (L[j]<L[minValue]){
minValue = j;
}
}
if (minValue!=i){}
swapData(L,minValue,i);
}
}
int main()
{
vector<int> L={1,3,6,8,4,6,99,77};
int length = L.size();
selectSort(L,length);
for (int i=0;i<length;++i)
cout<<L[i]<<endl;
}
3 直接插入排序:
//直接插入排序;
void swapData(vector<int>& L,int i,int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
void insertSort(vector<int>& L,int length)
{
int i,j;
for (i=1;i<length;++i){
if (L[i]<L[i-1]){
int temp = L[i];
for (j=i-1;j>0&&L[j]>temp;--j){
L[j+1] = L[j];
}
L[j+1] = temp;
}
}
}
int main()
{
vector<int> L={1,3,6,8,4,6,99,77};
int length = L.size();
insertSort(L,length);
for (int i=0;i<length;++i){
cout<<L[i]<<endl;
}
}
4 快速排序:
//快速排序;
void swapData(vector<int>& L,int i,int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
int partion(vector<int>& L,int low,int high)
{
while (low<high){
//int temp = L[low];
while(low<high && L[high]>=L[low])
--high;
swapData(L,low,high);
while(low<high && L[low]<=L[high])
++low;
swapData(L,low,high);
}
return low;
}
void qsort(vector<int>& L, int low, int high)
{
if (low<high){
int middle = partion(L,low,high);
qsort(L,low,middle-1);
qsort(L,middle+1,high);
}
}
void quickSort(vector<int>& L,int length)
{
qsort(L,0,length-1);
}
int main()
{
vector<int> L={1,3,6,8,4,6,99,77};
int length = L.size();
quickSort(L,length);
for (int i=0;i<length;++i)
cout<<L[i]<<endl;
}
5 堆排序:
//堆排序(排序出错,把整棵树画出来分析,找到错误原因);
void swapData(vector<int>& L,int i,int j)
{
int temp = L[i];
L[i] = L[j];
L[j] = temp;
}
void hSort(vector<int>& L, int i, int length)
{
int j,temp;
temp = L[i];
for (j=2*i;j<=length;j*=2){
if (j<length && L[j]<L[j+1])
++j;
if (L[j]<=temp)
break;
L[i] = L[j];
i = j;
}
L[i] = temp;
}
void heapSort(vector<int>& L, int length)
{
int i,j;
for (i=length/2;i>0;--i)
hSort(L,i,length);
for (j=length;j>1;--j){
swapData(L,1,j);
hSort(L,1,j-1);
}
}
int main()
{
vector<int> L = {1,3,6,8,4,6,99,77,88};
int length = L.size();
L.insert(L.begin(),0);
heapSort(L,length);
for (int i=1;i<=length;++i)
cout<<L[i]<<endl;
}