Skip to content

Commit db8bdec

Browse files
committed
added median of two sorted arrays cpp
1 parent 3f4f180 commit db8bdec

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <vector>
2+
3+
// Runtime: 20 ms, faster than 72.52% of C++ online submissions for Median of Two Sorted Arrays.
4+
// Memory Usage: 10.6 MB, less than 21.65% of C++ online submissions for Median of Two Sorted Arrays.
5+
// 02/23/2020
6+
// MM/DD/YYYY
7+
// Suprisingly, shell sort has the fastest runtime for this method out of other sorting algorithms, such as
8+
// quicksort, merge sort, and merging (from merge sort)
9+
10+
std::vector<int> shell_sort(std::vector<int> &array) {
11+
int gap = array.size()/2;
12+
while (gap >= 1) {
13+
for (int i = gap; i < array.size(); i++) { //iterate through array, starting from gap
14+
int comparator = array[i]; //make comparisons with this
15+
int output; //for accessing x outside the array
16+
int index; //for negative indexes
17+
18+
for (int x = i; x > gap-2; x -= gap) { //iterate throguh array with gap as the step
19+
output = x; //to access x outside the loop
20+
if (x-gap < 0) { //in case of negative index
21+
index = array.size()-x-gap;
22+
} else {
23+
index = x-gap;
24+
}
25+
26+
if (array[index] <= comparator) { //break when correct spot is found
27+
break;
28+
} else { //otherwise, move elements forward to make space
29+
array[x] = array[index];
30+
}
31+
}
32+
array[output] = comparator; //insert comparator in the correct spot
33+
}
34+
gap /= 2; //increment the gap
35+
}
36+
return array;
37+
}
38+
39+
std::vector<int> combine(std::vector<int> &array1, std::vector<int> &array2) {
40+
std::vector<int> array = array1;
41+
array.insert(array.end(), array2.begin(), array2.end());
42+
return array;
43+
}
44+
45+
class Solution {
46+
public:
47+
double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2) {
48+
std::vector<int> array = combine(nums1, nums2);
49+
std::vector<int> sorted = shell_sort(array);
50+
if (array.size() % 2 == 1) {
51+
return array[double(array.size())/2];
52+
} else {
53+
return double(array[float(array.size())/2] + array[float(array.size())/2-1]) / 2;
54+
}
55+
}
56+
};

0 commit comments

Comments
 (0)