排序算法

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)

算法实现:

  1. void mergearray(int a[], int first, int mid, int last, int temp[])  
  2. {  
  3.     int i = first, j = mid + 1;  
  4.     int m = mid,   n = last;  
  5.     int k = 0;  
  6.       
  7.     while (i <= m && j <= n)  
  8.     {  
  9.         if (a[i] <= a[j])  
  10.             temp[k++] = a[i++];  
  11.         else  
  12.             temp[k++] = a[j++];  
  13.     }  
  14.       
  15.     while (i <= m)  
  16.         temp[k++] = a[i++];  
  17.       
  18.     while (j <= n)  
  19.         temp[k++] = a[j++];  
  20.       
  21.     for (i = 0; i < k; i++)  
  22.         a[first + i] = temp[i];  
  23. }  
  24. void mergesort(int a[], int first, int last, int temp[])  
  25. {  
  26.     if (first < last)  
  27.     {  
  28.         int mid = (first + last) / 2;  
  29.         mergesort(a, first, mid, temp);    //左边有序  
  30.         mergesort(a, mid + 1, last, temp); //右边有序  
  31.         mergearray(a, first, mid, last, temp); //再将二个有序数列合并  
  32.     }  
  33. }  
  34.   
  35. bool MergeSort(int a[], int n)  
  36. {  
  37.     int *p = new int[n];  
  38.     if (p == NULL)  
  39.         return false;  
  40.     mergesort(a, 0, n - 1, p);  
  41.     delete[] p;  
  42.     return true;  
  43. }  

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;  
            }  
        }  
}  


各算法效率对比:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值