数据结构与算法—复习:直接选择排序 堆排序
#include <stdio.h>
#include <malloc.h>
struct RecordNode {
int key;
char info;
};
typedef struct RecordNode* PRecordNode;
struct SortObject{
int n;
PRecordNode record;
};
typedef struct SortObject* PSortObject;
PSortObject createEmptySortObject(int m){
PSortObject pvector = (PSortObject)malloc(sizeof(struct SortObject));
if(pvector != NULL){
pvector->record = (PRecordNode)malloc(sizeof(PRecordNode) * m);
if(pvector->record){
pvector->n = m;
return pvector;
}
printf("分配记录表时出错\n");
return pvector;
}
printf("分配排序目标时出错\n");
return pvector;
}
void init(PSortObject pvector,char* info,int* key,int n){
pvector->n = n;
for (int i = 0; i < n; ++i) {
pvector->record[i].info = info[i];
pvector->record[i].key = key[i];
}
}
void printRecord(PSortObject pvector){
for (int i = 0; i < pvector->n; ++i) {
printf("[%d,%c] ",pvector->record[i].key,pvector->record[i].info);
if(i + 1 == pvector->n){
printf("\n");
}
}
}
void selectSort(PSortObject pvector){
int i,j,
min;
struct RecordNode temp;
for (i = 0; i < pvector->n - 1; ++i) {
min = i;
for (j = i; j < pvector->n; ++j) {
if(pvector->record[j].key < pvector->record[min].key){
min = j;
}
}
if(i != min){
temp = pvector->record[i];
pvector->record[i] = pvector->record[min];
pvector->record[min] = temp;
}
}
}
void sift(PSortObject pvector,int size,int p){
int ch = 2 * p + 1;
struct RecordNode temp = pvector->record[p];
while (ch < size){
if(ch < (size - 1) && pvector->record[ch].key < pvector->record[ch+1].key){
ch++;
}
if(temp.key < pvector->record[ch].key){
pvector->record[p] = pvector->record[ch];
p = ch; ch = (2 * p) + 1;
} else break;
}
pvector->record[p] = temp;
}
void heapSort(PSortObject pvector){
int i,
n = pvector->n;
struct RecordNode temp;
for (i = n/2-1; i>=0 ; i--) {
sift(pvector,n,i);
}
for (i = pvector->n - 1; i > 0; --i) {
temp = pvector->record[0];
pvector->record[0] = pvector->record[i];
pvector->record[i] = temp;
sift(pvector,n,0);
}
}
int main() {
PSortObject pvector = createEmptySortObject(8);
char info[] = {'i','q','c','v','h','k','p','t'};
int key[] = {49,38,65,97,76,13,27,49};
int size = sizeof(key) / sizeof(int);
init(pvector,info,key,size);
printRecord(pvector);
heapSort(pvector);
printRecord(pvector);
}