1.快速排序算法:
时间复杂度:O(n*lgn)
最坏:O(n^2)
空间复杂度:O(n*lgn)
算法实现:
void quicksort(int v[], int left, int right){
if(left < right){
int key = v[left];
int low = left;
int high = right;
while(low < high){
while(low < high && v[high] > key){
high--;
}
v[low] = v[high];
while(low < high && v[low] < key){
low++;
}
v[high] = v[low];
}
v[low] = key;
quicksort(v,left,low-1);
quicksort(v,low+1,right);
}
}
2.插入排序算法:
时间复杂度:O(n^2)
算法实现:
void simple_insertSort(int array[], int n)
{
int i, j;
int temp;
for(i = 1; i < n; ++i)
{
temp = array[i];
j = i - 1;
while(j >= 0 && temp < array[j])
{
array[j+1] = array[j];
--j;
}
array[j+1] = temp;
}
}
3.归并排序算法:
时间复杂度:O(n*lgn)
算法实现:
- void mergearray(int a[], int first, int mid, int last, int temp[])
- {
- int i = first, j = mid + 1;
- int m = mid, n = last;
- int k = 0;
- while (i <= m && j <= n)
- {
- if (a[i] <= a[j])
- temp[k++] = a[i++];
- else
- temp[k++] = a[j++];
- }
- while (i <= m)
- temp[k++] = a[i++];
- while (j <= n)
- temp[k++] = a[j++];
- for (i = 0; i < k; i++)
- a[first + i] = temp[i];
- }
- void mergesort(int a[], int first, int last, int temp[])
- {
- if (first < last)
- {
- int mid = (first + last) / 2;
- mergesort(a, first, mid, temp); //左边有序
- mergesort(a, mid + 1, last, temp); //右边有序
- mergearray(a, first, mid, last, temp); //再将二个有序数列合并
- }
- }
- bool MergeSort(int a[], int n)
- {
- int *p = new int[n];
- if (p == NULL)
- return false;
- mergesort(a, 0, n - 1, p);
- delete[] p;
- return true;
- }
4.冒泡排序算法:
时间复杂度:O(n^2)
算法实现:
void bubble_sort(int a[],int n)//n为数组a的元素个数
{
int i,j,temp;
for(j=0;j<n-1;j++)
for(i=0;i<n-1-j;i++)
{
if(a[i]>a[i+1])//数组元素大小按升序排列
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
各算法效率对比: