File tree Expand file tree Collapse file tree 2 files changed +85
-0
lines changed
Competitive Coding/Sorting/Heap Sort Expand file tree Collapse file tree 2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ #define rep (i,a,b,c ) for (i=a;i<b;i+=c)
4
+ #define repp (i,a,b,c ) for (i=a;i>b;i+=c)
5
+
6
+ // --------------------------------------Heapify
7
+ void max_heapify (int *a, int i, int n)
8
+ {
9
+ int l=2 *i+1 ;
10
+ int r=2 *i+2 ;
11
+ int largest=0 ;
12
+ if (l<=n and a[l]>a[i])
13
+ largest=l;
14
+ else
15
+ largest=i;
16
+ if (r<=n and a[r]>a[largest])
17
+ largest=r;
18
+ if (largest!=i)
19
+ {
20
+ swap (a[largest],a[i]);
21
+ max_heapify (a,largest,n);
22
+ }
23
+ }
24
+ // ---------------------------------Build max Heap
25
+ void build_maxheap (int *a, int n)
26
+ {
27
+ int i;
28
+ repp (i,n/2 ,-1 ,-1 )
29
+ {
30
+ max_heapify (a,i,n);
31
+ }
32
+ }
33
+
34
+ // -----------------------------------HeapSort
35
+ void heapsort (int *a, int n)
36
+ {
37
+ int i;
38
+ build_maxheap (a,n);
39
+ repp (i,n,-1 ,-1 )
40
+ {
41
+ swap (a[0 ],a[i]);
42
+ n--;
43
+ max_heapify (a,0 ,n);
44
+ }
45
+ }
46
+
47
+ int main ()
48
+ {
49
+ int n, i, x;
50
+ cout<<" Enter no of elements of array\n " ;
51
+ cin>>n;
52
+
53
+ // Dynamic Memory Allocation
54
+ int *dynamic;
55
+ dynamic = new int [n];
56
+
57
+ // Input Of Elements
58
+ cout<<" Enter the elements of array :\n " ;
59
+ rep (i,0 ,n,1 )
60
+ cin>>dynamic[i];
61
+
62
+ heapsort (dynamic,n-1 );
63
+ // Sorted Array using heap sort
64
+ cout<< " Sorted Sequence is : " ;
65
+
66
+ rep (i,0 ,n,1 )
67
+ cout<< dynamic[i]<<" \t " ;
68
+ delete [] dynamic;
69
+ }
Original file line number Diff line number Diff line change
1
+ # Heap sort is a comparison based sorting technique based on Binary Heap data structure.
2
+ # Heapsort is an in-place algorithm, but it is not a stable sort.
3
+ # Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios.
4
+ # In max-heaps, maximum element will always be at the root. Heap Sort uses this property of heap to sort the array.
5
+
6
+ Heap sort algorithm is divided into two basic parts :
7
+ (1) Creating a Heap of the unsorted list.
8
+ (2) Then a sorted array is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the array.
9
+ {3) The heap is reconstructed after each removal.
10
+
11
+ Time Complexity: Time complexity of heapify is O(logn).
12
+ Time complexity of BUILD-MAX-HEAP(A) is O(n)
13
+ and we run max_heapify N−1 times in heap_sort function,
14
+ therefore complexity of heap_sort function in each case (Best, worst and average) is O(nlogn)
15
+
16
+ Space Complexity: O(1)
You can’t perform that action at this time.
0 commit comments