Skip to content

Commit

Permalink
feat:堆排序
Browse files Browse the repository at this point in the history
  • Loading branch information
JalorOo committed Dec 25, 2020
1 parent da00fbe commit 6c2048d
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 9 deletions.
57 changes: 57 additions & 0 deletions ADT/HEAP.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//
// HEAP.cpp
// ADT
//
// Created by Jalor on 2020/12/25.
// Copyright © 2020 Jalor. All rights reserved.
//

#include "HEAP.hpp"

void Heap::onCreate(){
int i = 0;
srand(time(NULL));
for (i = 1; i <= MAX; i++) {
a[i] = 1 + rand() % 100;
}
}//创建数组

void Heap::heapSort(int n){
int i = 0;
for (i = n/2; i >= 1; i--) {//从最后一个非叶子结点开始堆调整
Sift(i,n);
}
for (i = 1; i < n; i++) {//头与尾交换排序
a[0] = a[1];
a[1] = a[n - i + 1];
a[n - i + 1] = a[0];
Sift(1, n - i);//调整堆
}
}//堆排序

void Heap::outArray(){
for (int i = 1; i <= MAX; i++) {
cout<<" "<<a[i];
}
}//输出

void Heap::Sift(int k,int m){
int i = k,j = 2 * i;
while (j <= m) {
if (j < m && a[j] < a[j+1]) {//指向孩子中的最大者
j++;
}
if (a[i] > a[j]) {//若已经排序完成,则不再进行排序
break;
} else {//调整父母与孩子的位置,使之满足堆的定义
a[0] = a[i];
a[i] = a[j];
a[j] = a[0];

//孩子打乱了,对孩子进行堆调整。

i = j;
j = 2 * i;
}
}
}//堆调整
29 changes: 29 additions & 0 deletions ADT/HEAP.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//
// HEAP.hpp
// ADT
//
// Created by Jalor on 2020/12/25.
// Copyright © 2020 Jalor. All rights reserved.
//

#ifndef HEAP_hpp
#define HEAP_hpp

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

const int MAX = 10;

class Heap {
private:
int a[MAX+1] = {0};
void Sift(int,int);//堆调整
public:
void onCreate();//创建数组
void heapSort(int);//堆排序
void outArray();//输出
};

#endif /* HEAP_hpp */
16 changes: 7 additions & 9 deletions ADT/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// Copyright © 2020 Jalor. All rights reserved.
//
#include <iostream>
#include "HASH.hpp"
#include "HEAP.hpp"
using namespace std;

int main(int argc, const char * argv[]) {
Expand All @@ -27,13 +27,11 @@ int main(int argc, const char * argv[]) {
// int f[TSP_MAX] = {1};
// tsp.setStart(0);
// tsp.outSolution(s,f);
int vert[9] = {47,7,29,11,16,92,22,8,3};
Hash ha = Hash(vert,9,LINEAR);
ha.outHash();
int var;
while (1) {
cin>>var;
cout<<ha.search(var)<<" "<<ha.di<<endl;
}
Heap heap;
heap.onCreate();
heap.outArray();
cout<<endl;
heap.heapSort(MAX);
heap.outArray();
return 0;
}

0 comments on commit 6c2048d

Please sign in to comment.