diff --git a/src-c/HeapSort.c b/src-c/HeapSort.c new file mode 100644 index 0000000..6eb4b29 --- /dev/null +++ b/src-c/HeapSort.c @@ -0,0 +1,55 @@ +#include + +void main() +{ + int heap[10], no, i, j, c, root, temp; + + printf("\n Enter no of elements :"); + scanf("%d", &no); + printf("\n Enter the numbers : "); + for (i = 0; i < no; i++) + scanf("%d", &heap[i]); + for (i = 1; i < no; i++) + { + c = i; + do + { + root = (c - 1) / 2; + if (heap[root] < heap[c]) /* to create MAX heap array */ + { + temp = heap[root]; + heap[root] = heap[c]; + heap[c] = temp; + } + c = root; + } while (c != 0); + } + + printf("Heap array : "); + for (i = 0; i < no; i++) + printf("%d\t ", heap[i]); + for (j = no - 1; j >= 0; j--) + { + temp = heap[0]; + heap[0] = heap[j]; /* swap max element with rightmost leaf element */ + heap[j] = temp; + root = 0; + do + { + c = 2 * root + 1; /* left node of root element */ + if ((heap[c] < heap[c + 1]) && c < j-1) + c++; + if (heap[root] +void shellsort(int arr[], int num) +{ + int i, j, k, tmp; + for (i = num / 2; i > 0; i = i / 2) + { + for (j = i; j < num; j++) + { + for(k = j - i; k >= 0; k = k - i) + { + if (arr[k+i] >= arr[k]) + break; + else + { + tmp = arr[k]; + arr[k] = arr[k+i]; + arr[k+i] = tmp; + } + } + } + } +} +int main() +{ + int arr[30]; + int k, num; + printf("Enter total no. of elements : "); + scanf("%d", &num); + printf("\nEnter %d numbers: ", num); + + for (k = 0 ; k < num; k++) + { + scanf("%d", &arr[k]); + } + shellsort(arr, num); + printf("\n Sorted array is: "); + for (k = 0; k < num; k++) + printf("%d ", arr[k]); + return 0; +} \ No newline at end of file