順序表實現二分排序

AlberTeslaWizard發表於2020-11-22
/*
	Author:Albert Tesla Wizard
	Time:2020/11/22 14:10
*/
#include<bits/stdc++.h>
#define MAXSIZE 1000
using namespace std;
struct Sqlist
{
    int* elem;
    int length;
};
int BinarySort(Sqlist&L);
int create(Sqlist&L,int a[],int n)
{
    L.elem=new int[MAXSIZE];
    L.length=0;
    for(int i=0;i<n;i++){L.elem[i+1]=a[i];L.length++;}
}
void print(Sqlist L)
{
    for(int i=1;i<=L.length;i++)cout<<L.elem[i]<<" ";
    cout<<'\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    Sqlist L;
    int a[10]={4,5,3,1,2,6,9,7,8,10};
    create(L,a,10);
    print(L);
    BinarySort(L);
    print(L);
    return 0;
}
int BinarySort(Sqlist&L)
{
    for(int i=2;i<=L.length;i++)
    {
        L.elem[0]=L.elem[i];
        int low=1,high=i-1;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(L.elem[0]<L.elem[mid])high=mid-1;
            else low=mid+1;
        }
        for(int j=i-1;j>=high+1;j--)L.elem[j+1]=L.elem[j];
        L.elem[high+1]=L.elem[0];
    }
}

相關文章