#include <iostream>
using namespace std;
void Sift(int r[], int i, int n){
int j = 2*i+1;
int temp;
while (j <= n){
if(j<n && r[j]<r[j+1]){
j++;
}
if(r[i] > r[j]){
break;
}
else{
temp = r[i];
r[i] = r[j];
r[j] = temp;
i = j;
j = 2*i+1;
}
}
}
void HeapSort(int r[], int n){
int temp;
int i;
for(i=n/2; i>=0; i--){
Sift(r, i, n);
}
for(i=0; i<n; i++){
temp = r[0];
r[0] = r[n-i];
r[n-i] = temp;
Sift(r, 0, n-i-1);
}
}
int main ()
{
int array[] = {36, 30, 18, 40, 32, 45, 22, 50};
HeapSort(array, 7);
for (int i=0; i<8; i++){
cout << array[i] << " " ;
}
return 0;
}
堆排序一
最新推荐文章于 2024-07-25 17:57:45 发布