You are on page 1of 3

#include <stdio.

h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* prev;
struct Node* next;
} Node;

Node* criarNo(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

void inserirInicio(Node** head, int data) {


Node* newNode = criarNo(data);
if (*head == NULL) {
*head = newNode;
} else {
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
}
}

void imprimirLista(Node* head) {


Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

void trocar(Node* a, Node* b) {


int temp = a->data;
a->data = b->data;
b->data = temp;
}

void maxHeapify(Node* arr[], int tamanho, int i) {


int maior = i;
int esq = 2 * i + 1;
int dir = 2 * i + 2;

if (esq < tamanho && arr[esq]->data > arr[maior]->data)


maior = esq;
if (dir < tamanho && arr[dir]->data > arr[maior]->data)
maior = dir;

if (maior != i) {
trocar(arr[i], arr[maior]);
maxHeapify(arr, tamanho, maior);
}
}

void construirHeap(Node* arr[], int tamanho) {


int i = tamanho / 2 - 1;
for (; i >= 0; i--)
maxHeapify(arr, tamanho, i);
}

void heapSort(Node* arr[], int tamanho) {


construirHeap(arr, tamanho);

for (int i = tamanho - 1; i > 0; i--) {


trocar(arr[0], arr[i]);
maxHeapify(arr, i, 0);
}
}

void ordenarLista(Node* head) {


int tamanhoLista = 0;
Node* temp = head;
while (temp != NULL) {
tamanhoLista++;
temp = temp->next;
}

Node** arr = (Node**)malloc(tamanhoLista * sizeof(Node*));

temp = head;
for (int i = 0; i < tamanhoLista; i++) {
arr[i] = temp;
temp = temp->next;
}

heapSort(arr, tamanhoLista);

temp = head;
for (int i = 0; i < tamanhoLista; i++) {
temp->data = arr[i]->data;
temp = temp->next;
}

free(arr);
}

int main() {
Node* head = NULL;

inserirInicio(&head, 12);
inserirInicio(&head, 11);
inserirInicio(&head, 13);
inserirInicio(&head, 5);
inserirInicio(&head, 6);
inserirInicio(&head, 7);

printf("Lista original: ");


imprimirLista(head);

ordenarLista(head);

printf("Lista ordenada: ");


imprimirLista(head);

return 0;
}

You might also like