PAT1098 Insertion or Heap Sort
来源:互联网 发布:数据分析的意义 编辑:程序博客网 时间:2024/05/16 09:35
题目链接:
http://www.nowcoder.com/pat/5/problem/4322
题目大意:
判断插入排序还是堆排序。
首先判断下是哪种排序,是则以此排序方式再迭代一步。
代码:
#define _CRT_SECURE_NO_WARNINGS#include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>using namespace std;int dest[105];int N;int flag;bool isEqual(int* sort){ for (int i = 0; i < N; i++) { if (sort[i] != dest[i]) { return false; } } return true;}void Insertion_Sort(int* sort,int N){ for (int i = 1; i < N; i++) { int tmp = sort[i]; int j; for (j = i; j>0 && sort[j - 1] >= tmp; j--) { sort[j] = sort[j - 1]; } sort[j] = tmp; if (flag == 1) { return; } if (isEqual(sort)) { flag = 1; } }}void PercDown(int* sort,int parent,int n){ int child; int tmp = sort[parent]; for (; parent * 2+1 <= n-1; parent = child) { child = parent * 2+1; if (child != n-1 && sort[child] < sort[child + 1]) { child++; } if (tmp >= sort[child]) { break; } else { sort[parent] = sort[child]; } } sort[parent] = tmp;}void swap(int* a,int* b){ int tmp; tmp = *a; *a = *b; *b = tmp;}void Heap_Sort(int* sort,int N){ for (int i = N / 2; i >= 0; i--) //调成最大堆 { PercDown(sort,i,N); } for (int i = N - 1; i >= 0; i--) { swap(&sort[0],&sort[i]); PercDown(sort,0,i); if (flag == 2) { return; } if (isEqual(sort)) { flag = 2; } }}int main(){ int init[105]; int insertionSort[105]; int heapSort[105]; flag = 0; scanf("%d",&N); for (int i = 0; i < N; i++) { scanf("%d",&init[i]); } for (int i = 0; i < N; i++) { scanf("%d",&dest[i]); } for (int i = 0; i < N; i++) { insertionSort[i] = heapSort[i] = init[i]; } Insertion_Sort(insertionSort,N); Heap_Sort(heapSort,N); if (flag == 1) { printf("Insertion Sort\n"); printf("%d", insertionSort[0]); for (int i = 1; i < N; i++) { printf(" %d",insertionSort[i]); } } else if (flag == 2) { printf("Heap Sort\n"); printf("%d", heapSort[0]); for (int i = 1; i < N; i++) { printf(" %d", heapSort[i]); } } return 0;}
0 0
- PAT1098 Insertion or Heap Sort
- pat1098. Insertion or Heap Sort
- 1098.Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- 1098 Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- Insertion or Heap Sort (25)
- 1098. Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- PAT-Insertion or Heap Sort
- PAT 1098. Insertion or Heap Sort
- 1098. Insertion or Heap Sort (25)
- 1098. Insertion or Heap Sort (25)
- 1098. Insertion or Heap Sort (25)
- PAT 1098. Insertion or Heap Sort (25)
- pat 1098 Insertion or Heap Sort
- 09-排序3 Insertion or Heap Sort
- 基数排序
- 使用 WebSockets 进行 HTML5 视频直播
- 获取页面可视宽度(解决兼容性bug)
- WEB前端开发人员须知的常见浏览器兼容问题及解决技巧
- 管理培训决定企业生死的5个层面
- PAT1098 Insertion or Heap Sort
- iOS开发之涂鸦板
- Andriod中绘(画)图----Canvas的使用详解
- Qt树形控件QTreeView使用1——节点的添加删除操作
- 为什么接口里声明的都是常量
- Assembly的load, loadfrom, loadfile方法总结
- hadoop之combiners编程
- list与vector容器如何处理才能避免内存增长?
- Zookeeper选主流程和同步流程