1. 程式人生 > >7-1 排序 (25 分)

7-1 排序 (25 分)

題意:

對給出的數字按由小到大進行排序。

思路:

之前一直沒有用過堆排序,借這個題練習一下堆排序。

程式碼:

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define MAX 1e9;
#define FRE() freopen("in.txt","r",stdin)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 1000010;
int a[maxn];

struct HeapSort {
    
void adjustHeap(int* buf, int parent,int length) { int temp = buf[parent];//記錄父親節點 int child = parent*2;//獲得左孩子下標 while(child <= length) { if(child<length && buf[child]<buf[child+1]) {//如果範圍內的右孩子更大的話 child++; }
if(temp >= buf[child]) {//如果父親節點的值,比孩子最大值還要大,直接退出 break; } buf[parent] = buf[child];//將孩子節點值,賦給父親節點 parent = child;//從孩子開始繼續調整 child = child*2; } buf[parent] = temp; } void toSort(int* buf,int length) { for
(int i = length/2; i>0; i--) {//建堆 this->adjustHeap(buf, i, length); } for(int i = length; i>1; i--) { swap(buf[i], buf[1]);//將第一個數與當前的進行調換 this->adjustHeap(buf,1,i-1); } for(int i = 1; i<=length; i++) { if(i!=1) { printf(" "); } printf("%d",buf[i]); } } }; int main() { int n; cin>>n; for(int i = 1; i<=n; i++) { cin>>a[i]; } HeapSort hs; hs.toSort(a, n); return 0; }
View Code