快排(看了一篇博主的博客)

版权声明:欢迎转载!拒绝抄袭. https://blog.csdn.net/qq_36257146/article/details/88925867
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int t;

void quickSort(int a[],int s,int e,int k)
{
    if(s>=e) return;
    int q = a[s];//支点
    int i = s+1;
    int j = e;
    while(true)
    {
        while(a[j]>q) j--;
        while(a[i]<q&&i<e) i++;
        if(i<j)
        {
            swap(a[i++],a[j--]);
        }
        else
        {
            swap(a[j],a[s]);
            if(j == k) t = a[s];
            break;
        }

    }
    quickSort(a,s,j-1,k);
    quickSort(a,j+1,e,k);
}

void quickSort1(int a[],int s,int e)
{
    if(s>=e) return;
    int i = s;
    int j = e;
    int q = a[i];
    while(i!=j)
    {
        while(i<j&&a[j]>=q) j--;
        swap(a[i],a[j]);
        while(i<j&&a[i]<=q) i++;
        swap(a[i],a[j]);
    }//a[j] == q
    quickSort1(a,s,i-1);
    quickSort1(a,i+1,e);
}

void quickSort2(int a[],int s,int e)
{
    if(s>=e) return;
    int i = s;
    int j = e;
    int r = s+(e-s)/2;//中间值
    if(a[s]<a[r]) swap(a[s],a[r]);
    if(a[s]>a[e]) swap(a[s],a[e]);
    int q = a[s];
    while(1)
    {
        while(a[j]>q) j--;
        while(a[i]<q&&i<e) i++;
        if(i<j) swap(a[i++],a[j--]);
        else
        {
            swap(a[j],a[s]);
            break;
        }
    }
    quickSort2(a,s,j-1);
    quickSort2(a,j+1,e);

}


int main()
{
    int a[8] = {3,5,2,7,43,7,32,8};
    int k = 2;
//    quickSort(a,0,8-1,k);
//    cout<<t<<endl;
    quickSort2(a,0,7);
    for(int i = 0; i<8; i++)
    {
        cout<<a[i]<<" ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36257146/article/details/88925867