1098. Insertion or Heap Sort (25) 21'

简介: #include #include #include using namespace std;vector a, b;//note:堆排序从1开始void downAdjust(int low, int high...
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> a, b;
//note:堆排序从1开始
void downAdjust(int low, int high){
    int i = 1, j = i * 2;
    while (j <= high) {
        if(j + 1 <= high && b[j] < b[j] + 1)
            j = j + 1;
        if (b[i] < b[j]) {
            swap(b[i], b[j]);
            i = j;
            j = i * 2;
        }else break;
    }
}

int main(){
    int n;
    cin >> n;
    a.resize(n+1);
    b.resize(n+1);
    for (int i = 1; i <= n; i++)  cin >> a[i];
    for (int i = 1; i <= n; i++)  cin >> b[i];
    int i, j;
    for (i = 1; i <= n - 1 && b[i] <= b[i+1]; i++);
    for (j = i + 1; a[j] == b[j] && j <= n; j++) ;
    if (j == n+1) {
        cout << "Insertion Sort" << endl;
        sort(b.begin() + 1, b.begin() + i + 2);
    }else{
        cout << "Heap Sort" << endl;
        j = n;
        while(j >= 2 && b[j] >= b[j - 1]) j--;
        swap(b[1], b[j]);
        downAdjust(1, j - 1);
    }
    for (int i = 1; i <= n; i++)
        printf("%d%c", b[i], i == n ? '\n' : ' ');
    return 0;
}
目录
相关文章
|
3月前
|
搜索推荐 Python
堆排序(Heap Sort)
堆排序(Heap Sort)是一种选择排序算法,通过将待排序的元素构建成一个最大堆(或最小堆),然后将堆顶元素与堆尾元素交换,将堆的大小减一,再调整堆,使其重新满足最大堆(或最小堆)的性质。重复以上步骤,直到堆中只剩下一个元素,即排序完成。
24 2
|
6月前
|
存储 搜索推荐 算法
计数排序(Counting Sort)详解
计数排序(Counting Sort)是一种非比较排序算法,其核心思想是通过计数每个元素的出现次数来进行排序,适用于整数或有限范围内的非负整数排序。这个算法的特点是速度快且稳定,适用于某些特定场景。在本文中,我们将深入探讨计数排序的原理、步骤以及性能分析。
175 1
计数排序(Counting Sort)详解
|
9月前
|
算法 搜索推荐 Java
|
10月前
|
C++
【PAT甲级 - C++题解】1098 Insertion or Heap Sort
【PAT甲级 - C++题解】1098 Insertion or Heap Sort
61 0
2-路插入排序(Two-Way Insertion Sort)
算法介绍 算法描述 算法分析 代码实现 参考
LeetCode 143. Reorder List
给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
48 0
LeetCode 143. Reorder List
PAT (Advanced Level) Practice - 1098 Insertion or Heap Sort(25 分)
PAT (Advanced Level) Practice - 1098 Insertion or Heap Sort(25 分)
79 0
|
缓存 算法 搜索推荐
堆排序(Heap Sort)
算法介绍 算法描述 图片演示 动图演示 算法分析 代码实现 参考
堆排序(Heap Sort)