Implementation of Bubble Sort and Quick Sort in Exchange Sort

In the data structure, exchange sorting generally includes two sorting methods: one, bubble sort; two, quick sort

1. Bubble sort

在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒
void Bubble_sort(Seqlist &L,int n)   //冒泡排序
{
    for(int i=0;i<n-1;++i)//n个数据共需n-1趟比较
    {
        for(int j=0;j<n-i-1;++j)  //第i趟需要n-i-1次比较
        {
            if(L[j]>L[j+1])
            {
                swap(&L[j],&L[j+1]);
            }
        }
    }
}
void main()  //冒泡排序测试文件
{
    Seqlist L = {16,25,8,25,21,3,49,5};
    int n = 8;
    Bubble_sort(L,n);
    for(int i = 0;i < n;++i)  
    {
        cout<<L[i]<<"  ";
    }
}

2. Quick sort
1) Select a reference element, usually select the first element or the last element,
2) Divide the records to be sorted into two independent parts through one sorting, and the element values ​​of some of the records are higher than those of the reference element. value is small. Another part of the record has element values ​​that are greater than the reference value.
3) At this time, the reference element is in the correct position after it has
been sorted. 4) Then continue to sort the two parts of the records in the same way until the entire sequence is sorted.

int Partition(Seqlist &L,int left,int right)  //可以理解为将数据分段
{
    T pivotkey = L[left];//开始可以将最左边的数据设为关键值
    while(left<right)
    {
        while(left<right && L[right]>=pivotkey) //先从右边开始比较
        {
            right--;
        }
        L[left] = L[right];
        while(left<right && L[left]< pivotkey)
        {
            left++;
        }
        L[right]= L[left];
    }
    L[left] = pivotkey;
    return left;
}
void Quick_sort(Seqlist &L,int left,int right)
{
    if(left < right)
    {
        int pivotkey = Partition(L,left,right);  //确定基准元素位置
        Quick_sort(L,left,pivotkey -1);//递归对左边数据排序
        Quick_sort(L,pivotkey+1,right);//递归对右边数据排序
    }
}
快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。不稳定的排序

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324725045&siteId=291194637