冒泡、插入、堆排序整理

#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1001;
int n,s[maxn],heap[maxn];

void downAdjust(int low,int high)
{
    int i = low,j = i*2;
    while(j<=high)
    {
        if(j+1 <= high && heap[j] < heap[j+1])
            swap(heap[j],heap[j+1]);
        if(heap[j] > heap[i])
        {
            swap(heap[j],heap[i]);
            i = j;
            j = i*2;
        }
        else
            break;
    }
}

void creatHeap()
{
    for(int i = n/2;i>0;i--)
    {
        downAdjust(i,n);
    }
}

void heapSort()
{
    creatHeap();
    for(int i = n;i>0;i--)
    {
        swap(heap[1],heap[i]);
        downAdjust(1,i-1);
    }

}

void bubbleSort()
{
    for(int j = n - 1;j>0;j--)
    {
        int flag = 0;
        for(int i = 0;i<j;i++)
        {
            if(s[i]>s[i+1])
            {
                swap(s[i],s[i+1]);
                flag = 1;
            }
        }
        if(flag == 0) break;
    }

}

void inserSort()
{
    int j;
    for(int i = 1;i<n;i++)
    {
        int temp = s[i];
        for(j = i;j>0 && s[j-1] > temp;j--)
        {
            s[j] = s[j-1];
        }
        s[j] = temp;

    }
}



int main()
{
    freopen("1.txt","r",stdin);
    scanf("%d",&n);
    for(int i = 1;i<=n;i++)
        scanf("%d",&heap[i]);
//    inserSort();
//    bubbleSort();
    heapSort();
    for(int i = 1;i<=n;i++)
        printf("%d",heap[i]);


    return 0;
}

发布了111 篇原创文章 · 获赞 4 · 访问量 3208

猜你喜欢

转载自blog.csdn.net/qq_15556537/article/details/100850731
今日推荐