# TCS NQT Question Solve | 12 Sep | Slot 2 (V) | Codewindow.in ### Coding

#### Solution: In C++

``````#include
using namespace std;
int main()
{
int n;
cin &gt;&gt; n;
int arr[n];
for(int i = 0; i &gt; arr[i];
}
for(int i = 0; i &lt; n; i++)
{
for(int j = i+1; j  arr[j] )
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i = 0; i &lt; n; i++)
{
cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;
}
}``````

#### Solution: In c++

``````#include
using namespace std;
struct MinHeap {
unsigned size;
unsigned capacity;
int* harr;
};
struct MinHeap* createMinHeap(unsigned capacity)
{
struct MinHeap* minHeap = new MinHeap;
minHeap-&gt;size = 0;
minHeap-&gt;capacity = capacity;
minHeap-&gt;harr = new int[capacity];
return minHeap;
}
void swapMinHeapNode(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left size
&amp;&amp; minHeap-&gt;harr[left] harr[smallest])
smallest = left;
if (right size
&amp;&amp; minHeap-&gt;harr[right] harr[smallest])
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&amp;minHeap-&gt;harr[smallest], &amp;minHeap-&gt;harr[idx]);
minHeapify(minHeap, smallest);
}
}
int isSizeOne(struct MinHeap* minHeap)
{
return (minHeap-&gt;size == 1);
}
int extractMin(struct MinHeap* minHeap)
{
int temp = minHeap-&gt;harr;
minHeap-&gt;harr = minHeap-&gt;harr[minHeap-&gt;size - 1];
--minHeap-&gt;size;
minHeapify(minHeap, 0);
return temp;
}
void insertMinHeap(struct MinHeap* minHeap, int val)
{
++minHeap-&gt;size;
int i = minHeap-&gt;size - 1;
while (i &amp;&amp; (val harr[(i - 1) / 2])) {
minHeap-&gt;harr[i] = minHeap-&gt;harr[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap-&gt;harr[i] = val;
}
void buildMinHeap(struct MinHeap* minHeap)
{
int n = minHeap-&gt;size - 1;
int i;
for (i = (n - 1) / 2; i &gt;= 0; --i)
minHeapify(minHeap, i);
}
struct MinHeap* createAndBuildMinHeap(int len[], int size)
{
struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i harr[i] = len[i];
minHeap-&gt;size = size;
buildMinHeap(minHeap);
return minHeap;
}
int minCost(int len[], int n)
{
int cost = 0;
struct MinHeap* minHeap = createAndBuildMinHeap(len, n);
while (!isSizeOne(minHeap)) {
int min = extractMin(minHeap);
int sec_min = extractMin(minHeap);
cost += (min + sec_min);
insertMinHeap(minHeap, min + sec_min);
}
return cost;
}
int main()
{
int n;
cin &gt;&gt; n;
int arr[n];
for(int i = 0; i &gt; arr[i];
int size = sizeof(arr) / sizeof(arr);
cout &lt;&lt; minCost(arr, size);
return 0;
}``````