常见排序整理

常见数据结构和算法

排序(冒泡 插入 选择 归并 堆排序 快速 希尔 基数 )

排序中不稳定的 排序中与初始状态无关

口诀:选堆快希不稳 选堆归基不变

冒泡 时间:O(N^2) 空间: O(1)

思路:交换找出最大元素放置最前端。

void bubble_sort(int arr[],int len)
{
    for(int i=0;i<len;i++)
        for(int j=0;j<len-i-1;j++)//
        {
            if(arr[j]>arr[j+1])
            {
            int temp=arr[j];
            arr[j]=arr[j+1];
            arr[j+1]=temp;
            }
        }
}

快排 <分治法> 时间:O(nlogn) 空间:O(logn)

思路:随机找一个元素作为基准,将比它大的数字放在后边,比它小的数字放在前边

int Partition(int A[],int low,int high)
{
    int key=A[low];
    while(low<high)
    {
        while(low<high&&A[high]>=key)
        {
            --high;
        }
        A[low]=A[high];
        while(low<high &&A[low]<=key)
        {
            ++low;
        }
        A[high]=A[low];
    }
    A[low]=key;
    return low;
}
void QuickSort(int A[],int low,int high)
{
    if(low<high)
    {
        int middle=Partition(A,low,high);
        QuickSort(A,low,middle-1);
        QuickSort(A,middle+1,high);
    }
}

归并 时间复杂度O(nlogn) 空间复杂度O(n)

思路:划分成各个子序列进行排序 ,然后将子序列合并

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);
    }
}
void mergearray(int a[],int first,int mid,int last,int temp[])//合并序列
{
    int i=first;
    int j=mid+1;
    int k=0;
    while(i<=mid&&j<=last)
    {
        if(a[i]<=a[j])
            temp[k++]=a[i++];
        else
           temp[k++]=a[j++];
    }
    while(i<=mid)
        temp[k++]=a[i++];//当j>last时,序列最后的数字合并
    while(j<=n)
        temp[k++]=a[j++];
}

堆排序 时间复杂度O(nlogn) 空间复杂度 O(1)

思路:将待排序序列构造成一个大顶堆,此时,整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余n-1个元素重新构造成一个堆,这样会得到n个元素的次小值。

猜你喜欢

转载自www.cnblogs.com/alwayszzj/p/12441221.html