PAT1098 Insertion or Heap Sort
2015-11-26 15:15
393 查看
题目链接:
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; }
相关文章推荐
- 插入排序
- 堆排序
- C#堆排序实现方法
- php实现插入排序
- Java数据结构及算法实例:插入排序 Insertion Sort
- php堆排序实现原理与应用方法
- javascript数据结构之双链表插入排序实例详解
- C++堆排序算法的实现方法
- 深入理解堆排序及其分析
- C语言对堆排序一个算法思路和实现代码
- c++几种基本的插入排序(图文)
- Java排序算法总结之插入排序
- Java实现八个常用的排序算法:插入排序、冒泡排序、选择排序、希尔排序等
- JAVA算法起步之堆排序实例
- JAVA算法起步之插入排序实例
- java数组排序示例(冒泡排序、快速排序、希尔排序、选择排序)
- Java排序算法总结之堆排序
- python插入排序算法的实现代码
- libdvbpsi源码分析(四)PAT表解析/重建