1098挿入またはヒープの並べ替えをなでます

1098挿入またはヒープソート

ワード:

Insertion sort iterates
插入排序迭代 
consuming(消费) one input element each repetition,
每次重复使用一个输入元素,
and growing a sorted output list. 
并增加一个排序输出列表。
finds the location it belongs within(在...之中) the sorted list,
在排序列表中查找它所属的位置,
and it iteratively shrinks(缩小) the unsorted region by extracting(提取) the largest element and moving that to the sorted region.
通过提取最大元素并将其移动到排序区域,它迭代地缩小未排序区域。
it involves(包括,涉及) the use of a heap data structure rather than a linear-time search to find the maximum.
together with a sequence which is a result of several iterations of some sorting method
它使用堆数据结构,而不是线性时间搜索来找到最大值。
The last line contains the partially(部分) sorted sequence of the N numbers.
最后一行包含N个数字的部分排序序列

アイデア:

首先判断插入排序, 当找到一个点 a[i - 1] > a[i] , i就是不适配点

全ての点のソートされていない値のシーケンスと位置のソート位置が同じ位置なので、その挿入ソートに整合されていない場合

それ以外の場合はヒープソート、ヒープのソート順序の後部がソートされているので、

// 测试点 3 5 是堆结构
#include<bits/stdc++.h>
using namespace std;
const int maxsize = 505; //实际只用开题意要求的值 因为堆是完全二叉树, 结点序列值为 1-n
bool isHeap = false;
int a[maxsize], b[maxsize];
void justDown(int low, int high) { // 必须保证是堆结构
    int j = low * 2 + 1, i = low;
    while(j <= high) {
        if(j + 1 <= high && b[j + 1] > b[j]) j = j + 1; // 没有判断右结点的范围3测试点错误
        if(b[j] <= b[i]) break;
        swap(b[j], b[i]);
        i = j;
        j = j * 2 + 1; //最后一个测试点错误的原因 (找了一个小时) 下标是从0开始却写为了下标从1开始的位置
    }
}
int main()
{
    int n;
    scanf("%d", &n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    for(int i = 0; i < n; i++) {
        scanf("%d", &b[i]);
    }
    // 判断是什么类型的排序
    int k = 1;
    for(int i = 1; i < n; i++) {
        if(b[i - 1] > b[i]) {  // 此处比较的是已经排好序的数字
            k = i;
            //int j = k + 1; 不适配处也需要与未排序的位置进行比较,
            break;
        }
    }
    int index = k;
    for(; index < n && a[index] == b[index]; index++); // 需要判断
    if(index == n){
        printf("Insertion Sort\n");
        sort(b, b + k + 1);
    } else {
        printf("Heap Sort\n");
        int j = n - 1;
        for(; j > 1 && b[j] >= b[0]; j--); //
        swap(b[0], b[j]);   //
        justDown(0, j - 1); // 此处是j - 1 不是j 交换了的元素不应该继续调整
    }

    for(int i = 0; i < n; i++) { // 共同操作直接写在最后一步
        printf("%s%d", i == 0 ? "" : " ", b[i]);
    }
    return 0;
}

おすすめ

転載: www.cnblogs.com/csyxdh/p/12422208.html