1.插入排序
void InsertSort(int a[], int n)
{
int temp, i, j;
for (i = ; i < n; i++)
{
if (a[i] < a[i - ])
{
temp = a[i];
for (j = i - ; j >= && a[j]>temp; j--)
a[j + ] = a[j];
a[j + ] = temp;
}
}
}
时间复杂度:O(n2)
空间复杂度:O(1)
稳定性:稳定
2.希尔排序
void ShellSort(int a[], int n)
{
int dk,temp, i, j;
for (dk = n / ; dk >= ; dk /= )
{
for (i = dk; i <n; i+=dk)
{
if (a[i] < a[i - dk])
{
temp = a[i];
for (j = i - dk; j>=&&a[j]>temp; j -= dk)
a[j + dk] = a[j];
a[j + dk] = temp;
}
}
}
}
时间复杂度:O(n1.3)
最坏时间复杂度:O(n2)
空间复杂度:O(1)
稳定性:不稳定
3.冒泡排序
void BubbleSort(int a[], int n)
{
int temp,flag;
for (int i = ; i < n ; i++)
{
flag = ;
for (int j = ; j < n-i; j++)
{
if (a[j]>a[j + ])
{
temp = a[j];
a[j] = a[j + ];
a[j + ] = temp;
flag = ;
}
}
if (flag == ) break;
}
}
时间复杂度:O(n2)
空间复杂度:O(1)
稳定性:稳定
4.快速排序:O(nlog)---O(1)----稳定
int Parttion1(int a[], int low,int high)
{
int temp = a[low];
while (low < high)
{
while (low < high&&a[high] >= temp) high--;
a[low] = a[high];
while (low < high&&a[low] <= temp) low++;
a[high] = a[low];
}
a[low] = temp;
return low;
} void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int Parttion2(int a[], int low, int high)
{//将小于等于a[high]的元素移到最前面,最后再将a[high]移到最终位置
int temp = a[high];
int i = low - ;
for (int j = low; j < high; j++)
{
if (a[j] <= temp)
{
i++;
swap(a[i], a[j]);
}
}
swap(a[i + ], a[high]);
return i + ;
}
void QuickSort(int a[], int low, int high)
{
if (low < high)
{
int p = Parttion2(a, low, high);
QuickSort(a, low, p - );
QuickSort(a, p + , high);
}
}
时间复杂度:O(n2)--基本有序或逆序的情况
空间复杂度:O(n)
稳定性:不稳定
平均时间复杂度最好:O(nlog2n)
5.简单选择排序
void SelectSort(int a[], int n)
{
int min;
for (int i = ; i < n-; i++)
{
min = i;
for (int j = i+; j < n; j++)
{
if (a[j] < a[min])
min = j;
}
if (min!=i)
swap(a[min], a[i]);
}
}
时间复杂度:O(n2)
空间复杂度:O(1)
稳定性:不稳定
6.堆排序
void AdjustDown(int a[], int k, int n)
{
a[] = a[k]; //a[0]是暂存单元
for (int i = * k; i <= n; i *= )
{
if (i < n&&a[i] < a[i + ]) i++;
if (a[]>=a[i]) break;
else
{
a[k] = a[i];
k = i;
}
}
a[k] = a[];
} void AdjustUp(int a[], int k)
{
a[] = a[k];
for (int i = k / ; i > ; i /= )
{
if (a[i] > a[]) break;
else
{
a[k] = a[i];
k = i;
}
}
a[k] = a[];
} void BuildMaxHeap(int a[], int n)
{
/*for (int i = n / 2; i > 0; i--)
AdjustDown(a, i, n);*/
for (int i = n; i > ; i--)
AdjustUp(a, i);
} void HeapSort(int a[], int n)
{
BuildMaxHeap(a, n);
for (int i = n; i > ; i--)
{
swap(a[], a[i]);
AdjustDown(a, , i - );
}
}
时间复杂度:O(nlog2n)
空间复杂度:O(1)
稳定性:不稳定