Commit d857b114 authored by ARPIT AGGARWAL's avatar ARPIT AGGARWAL

update merge-sort to reflect API update

parent 2fac559b
#include "sorting.h" #include "sorting.h"
using namespace std ; using namespace std ;
//random //random
void merge(int arr[], int l, int m, int r) void merge(int arr[], int l, int m, int r)
{ {
int i, j, k; int i, j, k;
int n1 = m - l + 1; int n1 = m - l + 1;
int n2 = r - m; int n2 = r - m;
int L[n1], R[n2]; int L[n1], R[n2];
for (i = 0; i < n1; i++) for (i = 0; i < n1; i++)
L[i] = arr[l + i]; L[i] = arr[l + i];
for (j = 0; j < n2; j++) for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j]; R[j] = arr[m + 1+ j];
i = 0; i = 0;
j = 0; j = 0;
k = l; k = l;
while (i < n1 && j < n2) while (i < n1 && j < n2)
{ {
if (L[i] <= R[j]) if (L[i] <= R[j])
{ {
arr[k] = L[i]; arr[k] = L[i];
i++; i++;
} }
else else
{ {
arr[k] = R[j]; arr[k] = R[j];
j++; j++;
} }
k++; k++;
} }
while (i < n1) while (i < n1)
{ {
arr[k] = L[i]; arr[k] = L[i];
i++; i++;
k++; k++;
} }
while (j < n2) while (j < n2)
{ {
arr[k] = R[j]; arr[k] = R[j];
j++; j++;
k++; k++;
} }
} }
void mergeSort(int arr[], int l, int r) void mergeSort(int arr[], int l, int r)
{ {
if (l < r) if (l < r)
{ {
int m = l+(r-l)/2; int m = l+(r-l)/2;
mergeSort(arr, l, m); mergeSort(arr, l, m);
mergeSort(arr, m+1, r); mergeSort(arr, m+1, r);
merge(arr, l, m, r); merge(arr, l, m, r);
} }
} }
vector<int> sort_custom(vector<int> data) vector<int> sort_custom(vector<int> data, int startidx, int endidx)
{ {
//vector<int> arr(data.begin(), data.end()) ; //vector<int> arr(data.begin(), data.end()) ;
int n = data.size() ; int n = data.size() ;
...@@ -63,7 +63,7 @@ vector<int> sort_custom(vector<int> data) ...@@ -63,7 +63,7 @@ vector<int> sort_custom(vector<int> data)
{ {
arr[i] = data[i] ; arr[i] = data[i] ;
} }
mergeSort(arr,0,n-1) ; mergeSort(arr, startidx, endidx - 1) ;
vector<int> res(arr, arr+n) ; vector<int> res(arr, arr + n) ;
return res ; return res ;
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment