0% found this document useful (0 votes)
68 views2 pages

1156

The document contains C++ code to implement merge sort. It defines functions for merging two sorted arrays, recursively applying the merge sort algorithm, and printing the sorted array. The main function takes input array and index array, calls merge sort to sort the input array in place, and prints the sorted index array.

Uploaded by

Doina Mihailov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views2 pages

1156

The document contains C++ code to implement merge sort. It defines functions for merging two sorted arrays, recursively applying the merge sort algorithm, and printing the sorted array. The main function takes input array and index array, calls merge sort to sort the input array in place, and prints the sorted index array.

Uploaded by

Doina Mihailov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<iostream>

using namespace std;

void merge(int arr[], int l, int m, int r, int indici[])


{
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2], L2[n1], R2[n2];

for(int i = 0; i < n1; i++){


L[i] = arr[l + i];
L2[i] = indici[l + i];
}
for(int j = 0; j < n2; j++){
R[j] = arr[m + 1 + j];
R2[j] = indici[m + 1 + j];
}

int i = 0;

int j = 0;

int k = l;

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
arr[k] = L[i];
indici[k] = L2[i];
i++;
}
else
{
arr[k] = R[j];
indici[k] = R2[j];
j++;
}
k++;
}

while (i < n1)


{
arr[k] = L[i];
indici[k] = L2[i];
i++;
k++;
}

while (j < n2)


{
arr[k] = R[j];
indici[k] = R2[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r, int indici[])
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m, indici);
mergeSort(arr, m + 1, r, indici);

merge(arr, l, m, r, indici);
}
}

void printArray(int A[], int size)


{
for(int i = 0; i < size; i++)
cout << A[i] + 1 << " ";
}

int main()
{
int v[100001], n, i, indici[100001];

cin >> n;

for (i = 0; i < n; i++) {


cin >> v[i];
}

for(i = 0; i< n; i++)


indici[i]=i;

mergeSort(v, 0, n - 1, indici);
printArray(indici, n);
return 0;
}

You might also like