09-排序3 Insertion or Heap Sort
来源:互联网 发布:纸飞机软件exe 编辑:程序博客网 时间:2024/06/05 20:05
#include <stdio.h>#include <stdlib.h>void Insertion_Sort(int A[], int N);void PercDown(int A[], int i, int N);int compare(int a[], int b[], int N){for (int i = 0; i < N; i++){if (a[i] != b[i])return 0;}return 1;}void swap(int *a, int *b){int tmp;tmp = *a;*a = *b;*b = tmp;}void print(int a[], int N){for (int i = 0; i < N; i++){if (i == 0)printf("%d", a[i]);elseprintf(" %d", a[i]);}}int main(int argc, char const *argv[]){// freopen("test.txt", "r", stdin);int N;scanf("%d", &N);int a1[N], a2[N], b[N];for (int i = 0; i < N; i++){scanf("%d", &a1[i]);a2[i] = a1[i];}for (int i = 0; i < N; i++)scanf("%d", &b[i]);for (int i = 2; i <= N; i++){//要从2开始,不然测试点3(有测试点0的话就是测试点2)过不了Insertion_Sort(a1, i);if (compare(a1, b, N)){Insertion_Sort(a1, i+1);printf("Insertion Sort\n");print(a1, N);return 0;}}for (int i = (N-1)/2; i >= 0; i--)/* BuildHeap */ //这里是循环排成大根堆,建立初始堆; 因为从A[0]开始,所以(N-1)/2PercDown(a2, i, N);for (int i = N-1; i > 0; i--){swap(&a2[0], &a2[i]);PercDown(a2, 0, i);if (compare(a2, b, N)){swap(&a2[0], &a2[i-1]);PercDown(a2, 0, i-1);printf("Heap Sort\n");print(a2, N);return 0;}}return 0;}void Insertion_Sort(int A[], int N){for (int P = 1; P < N; P++){int tmp = A[P];int i;for (i = P; i > 0 && A[i-1] > tmp; i--)A[i] = A[i-1];A[i] = tmp;}}// void Heap_Sort(int A[], int N)// {// for (int i = (N-1)/2; i >= 0; i--)/* BuildHeap */ //这里是循环排成大根堆,建立初始堆; 因为从A[0]开始,所以(N-1)/2// PercDown(A, i, N);// for (int i = N-1; i > 0; i--){// swap(&A[0], &A[i]);// PercDown(A, 0, i);// }// }void PercDown(int A[], int i, int N)//这个是排成大根推的函数,A[]是接收一个数组,i为根节点,N为节点总数{int Child;int tmp;for (tmp = A[i]; 2*i+1 < N; i = Child){Child = 2*i+1;if (Child < N-1 && A[Child+1] > A[Child])Child++;if (tmp < A[Child])A[i] = A[Child];elsebreak;}A[i] = tmp;}
0 0
- 09-排序3 Insertion or Heap Sort
- 09-排序3 Insertion or Heap Sort
- 09-排序3 Insertion or Heap Sort (25分)
- 09-排序3 Insertion or Heap Sort (25分)
- 09-排序3 Insertion or Heap Sort (25分)
- PAT--1098. Insertion or Heap Sort(排序)
- 09-排序3 Insertion or Heap Sort (25分)
- 1098.Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- PAT1098 Insertion or Heap Sort
- 1098 Insertion or Heap Sort
- 1098. Insertion or Heap Sort
- pat1098. 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
- Scala之旅-环境配置
- POJ 3076 Sudoku (DLX解数独)
- 09-排序2 Insert or Merge
- 了解CMS(Concurrent Mark-Sweep)垃圾回收器
- 我最常用的编程风格
- 09-排序3 Insertion or Heap Sort
- java中的继承和接口
- 多态和内部类
- Tomcat 多实例
- POJ2773(容斥+二分)
- python概述以及安装环境和第一个程序以及一些语言基本语法
- 返回刚插入的数据的主键
- 海量数据挖掘MMDS week2: 局部敏感哈希Locality-Sensitive Hashing, LSH
- Git 解决冲突