Merge pull request #507 from ericcurtin/patch-1

heapsort does not work for sorted input 1,2,3,4,5
This commit is contained in:
Hai Hoang Dang 2020-01-03 19:19:05 -08:00 committed by GitHub
commit c896b07e89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,62 +1,60 @@
#include <stdio.h>
void heapify(int *unsorted, int index, int heap_size);
void heap_sort(int *unsorted, int n);
void max_heapify(int* a, int i, int n);
void heapsort(int* a, int n);
void build_maxheap(int* a, int n);
void max_heapify(int* a, int i, int n) {
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n) {
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (temp > a[j]) {
break;
} else if (temp <= a[j]) {
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = temp;
return;
}
void heapsort(int* a, int n) {
int i, temp;
for (i = n; i >= 2; i--) {
temp = a[i];
a[i] = a[1];
a[1] = temp;
max_heapify(a, 1, i - 1);
}
}
void build_maxheap(int* a, int n) {
int i;
for (i = n / 2; i >= 1; i--) {
max_heapify(a, i, n);
}
}
int main() {
int n = 0;
int i = 0;
char oper;
int n, i;
printf("Enter number of elements of array\n");
scanf("%d", &n);
int a[20];
for (i = 1; i <= n; i++) {
printf("Enter Element %d\n", i);
scanf("%d", a + i);
}
int* unsorted;
printf("Enter the size of the array you want\n");
scanf("%d", &n);
unsorted = (int*)malloc(sizeof(int) * n);
while (getchar() != '\n');
printf("Enter numbers separated by a comma:\n");
while (i != n) {
scanf("%d,", (unsorted + i));
i++;
}
heap_sort(unsorted, n);
build_maxheap(a, n);
heapsort(a, n);
printf("Sorted Output\n");
for (i = 1; i <= n; i++) {
printf("%d\n", a[i]);
}
printf("[");
printf("%d", *(unsorted));
for (int i = 1; i < n; i++) {
printf(", %d", *(unsorted + i));
}
printf("]");
}
void heapify(int *unsorted, int index, int heap_size) {
int temp;
int largest = index;
int left_index = 2 * index;
int right_index = 2 * index + 1;
if (left_index < heap_size && *(unsorted + left_index) > *(unsorted + largest)) {
largest = left_index;
}
if (right_index < heap_size && *(unsorted + right_index) > *(unsorted + largest)) {
largest = right_index;
}
if (largest != index) {
temp = *(unsorted + largest);
*(unsorted + largest) = *(unsorted + index);
*(unsorted + index) = temp;
heapify(unsorted, largest, heap_size);
}
}
void heap_sort(int *unsorted, int n) {
int temp;
for (int i = n / 2 - 1; i > -1; i--) {
heapify(unsorted, i, n);
}
for (int i = n - 1; i > 0; i--) {
temp = *(unsorted);
*(unsorted) = *(unsorted + i);
*(unsorted + i) = temp;
heapify(unsorted, 0, i);
}
getchar();
}