# Implement Merge Sort Problem

You are given an array of integers. You have to sort the array using merge sort algorithm.

Input/Output Format For The Function:

Input Format:

The function contains a single argument, an integer array arr.

Output Format:

Return the sorted integer array.

#### Solution

We have provided a solution which contains necessary comments to understand the approach used:

#### 1) recursive_solution.java

Description:

We are given an input array of integers. Now we will implement merge sort algorithm to sort the integers in this array. Merge sort algorithm is a divide and conquer algorithm. Here, we partition the given array into subarrays, sort each of the subarrays separately and then merge these sorted subarrays to get the final resultant sorted array.

For more details, refer to the code given in recursive_solution.java.

Time Complexity (assuming that input arguments are already given and excluding time used in declaration of output):

O(n*logn) where n denotes the length of array arr.

Here we keep on splitting the array into halves until we reach an array of size 1. For each of these subarrays, we sort them separately and merge them. Hence, after sorting and merging all the subarrays, the time complexity turns out to be O(n*logn).

Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.

T(n) = 2T(n/2) + Theta(n)

The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is Theta(n*logn).

Time complexity of MergeSort is Theta(n*logn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and take linear time to merge two halves.

Time Complexity:

O(n*logn) where n denotes the length of array arr.

As time complexity assuming that input arguments are already given and excluding time used in declaration of output is O(n*logn), to read input it will take O(n) and to store output it will take O(n) hence total complexity will be O(n*logn) + O(n) + O(n) → O(n*logn).

Auxiliary Space Used:

O(n) + O(logn)where n denotes the length of array arr.

Here, Merge Sort space complexity will always be O(n) with arrays. If you draw the space tree out, it will seem as though the space complexity is O(n*logn). However, as the code is a Depth First code, you will always only be expanding along one branch of the tree, therefore, the total space usage required will always be bounded by O(3n) = O(n). Apart from this, at each step, the size of the array gets halved, the depth of the tree would be at most O(logn). So considering functional stack space used for recursive calls the overall auxiliary space turns out to be O(n) + O(logn).

Space Complexity:

O(n) + O(logn) where n denotes the length of array arr.

The input array is of size n, so the input space complexity is O(n), and auxiliary space used is O(n) + O(logn) and output uses O(n), hence total complexity will be O(n) + O(logn) + O(n) + O(n) → O(n) + O(logn).

``````
// -------- START --------
public static List merge_sort(List arr) {
int n = arr.size();
int left = 0, right = n-1;
split(arr, left, right);
return arr;
}

/*function to partition the array into subarrays and then merge them*/
public static void split(List arr, int left, int right) {
if(left arr, int left, int mid, int right) {
int[] l = new int[mid - left + 1];
//copies the integers to array l from arr
for(int i = 0; i< mid - left + 1; i++) {
l[i] = arr.get(left + i);
}
int[] r = new int[right - mid];
//copies the integers to array r from arr
for(int i = 0; i< right - mid; i++) {
r[i] = arr.get(mid + i + 1);
}
int i = 0, j = 0, k = left;
//merges arrays l and r back to arr
while(i``````

#### `2) iterative_solution.java`

`Description:`

`We are given an input array of integers. Now the iterative approach of merge sort algorithm to sort given array. We start by dividing the array into blocks of size 1,2,4,8... and so on. For each of these blocks, we divide the array into corresponding subarrays of the size equal to block size and then sort them. Finally, we merge the sorted arrays and obtain the final sorted array. For more details, refer to the code given in iterative_solution.java.`

`Time Complexity (assuming that input arguments are already given and excluding time used in declaration of output):`

`O(n*logn) where n denotes the length of array arr.`

`Here we iterate over block sizes starting from 1 and then move on in multiples of 2, that is, 2, 4, 8... and so on. For each of these block sizes, we take 2 consecutive subarrays of that size over the entire array. So for a block size of 1, there will be 2 subarrays of size 1 and we then sort them separately and merge them. We do this over the entire array n. So for each block size, we require O(n) time to sort the subarrays and merge them. Hence, after sorting and merging all the subarrays, for all the block sizes, 1,2,4,8,...,log2(n) the time complexity turns out to be O(n*logn).`

`Time Complexity:`

`O(n*logn) where n denotes the length of array arr.`

`As time complexity assuming that input arguments are already given and excluding time used in declaration of output is O(n*logn), to read input it will take O(n) and to store output it will take O(n) hence total complexity will be O(n*logn) + O(n) + O(n) → O(n*logn).`

`Auxiliary Space Used:`

`O(n*logn) where n denotes the length of array arr.`

`Here, for each and every subarray, we create a new array and copy the corresponding elements from the original array into this new array. So, total space complexity required is O(n*logn).`

`Space Complexity:`

`O(n*logn) where n denotes the length of array arr.`

`The input array is of size n, so the input space complexity is O(n), and auxiliary space used is O(n*logn) and output uses O(n), hence total complexity will be O(n*logn) + O(n) + O(n) → O(n*logn).`

``````
// -------- START --------
public static List merge_sort(List arr) {
int n = arr.size();
int left = 0, right = n-1;
split(arr, left, right);
return arr;
}

public static void split(List arr, int l, int h) {
// divide the array into blocks of size [1,2,4,8,..]
for (int blocks = 1; blocks <= h - l; blocks = 2 * blocks) {
// for blocks = 1, i = 0, 2, 4, 6, 8 and so on
// for each block we split the array into sub arrays and merge them
/* note that each of these subarrays will always be sorted as we are
building the array from smaller subarrays to larger subarrays*/
for (int i = l; i < h; i += 2 * blocks) {
int left = i;
int mid = Math.min(i + blocks - 1, h);
int right = Math.min(i + 2 * blocks - 1, h);
merge(arr, left, mid, right);
}
}
}

/*function to merge 2 sorted arrays*/
public static void merge(List arr, int left, int mid, int right) {
int[] l = new int[mid - left + 1];
//copies the integers to array l from arr
for(int i = 0; i< mid - left + 1; i++) {
l[i] = arr.get(left + i);
}
int[] r = new int[right - mid];
//copies the integers to array r from arr
for(int i = 0; i< right - mid; i++) {
r[i] = arr.get(mid + i + 1);
}
int i = 0, j = 0, k = left;
//merges arrays l and r back to arr
while(i``````

`Additional Material`

##### `QuickSort vs MergeSort:`

`Quicksort is an in-place sorting algorithm, that is, it does not require any extra space to perform sorting of an array. On the other hand, merge sort requires O(n*logn) auxiliary space. However, the worst-case time complexity of quicksort is O(n^2) because the time complexity depends on the selection of pivot. On the other hand, for mergesort, the worst-case time complexity is always O(n*logn).`

### `Attend our Free Webinar on How to Nail Your Next Technical Interview`

#### `Recommended Posts`

`Print Matrix In Spiral Order Problem`
`Skyline Problem`
`Number Of Ways To Make Change Problem`
`All Posts`
``` window.cookieconsent.initialise({palette:{popup:{background:"#3996d2",text:"#ffffff"},button:{background:"#00d1b4",text:"#ffffff"}},theme:"classic",content:{message:"We use cookies to enable the best possible experience on our site and to optimize the content for you. If you continue surfing you agree.",href:"https://www.interviewkickstart.com/privacy-policy"}}); function getAllUrlParams(url) { var queryString = url ? url.split('?') : window.location.search.slice(1); var utmobj = {}; if (queryString) { queryString = queryString.split('#'); var arr = queryString.split('&'); for (var i = 0; i < arr.length; i++) { var a = arr[i].split('='); var paramName = a; var paramValue = typeof (a) === 'undefined' ? true : a; paramName = paramName.toLowerCase(); if (paramName.match(/\[(\d+)?\]\$/)) { var key = paramName.replace(/\[(\d+)?\]/, ''); if (!utmobj[key]) utmobj[key] = []; if (paramName.match(/\[\d+\]\$/)) { var index = /\[(\d+)\]/.exec(paramName); utmobj[key][index] = paramValue; } else { utmobj[key].push(paramValue); } } else { if (!utmobj[paramName]) { utmobj[paramName] = paramValue; } else if (utmobj[paramName] && typeof utmobj[paramName] === 'string'){ utmobj[paramName] = [utmobj[paramName]]; utmobj[paramName].push(paramValue); } else { utmobj[paramName].push(paramValue); } } } } return utmobj; } function create_UUID() { function _p8(s) { var p = (Math.random().toString(16)+"000000000").substr(2,8); return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ; } return _p8() + _p8(true) + _p8(true) + _p8(); } var visitor_id = getCookie("unique_visitor_id6"); var expdate = new Date(); expdate.setTime(expdate.getTime()+(365*24*60*60*1000)); if(visitor_id == ""){ setCookie("unique_visitor_id6",create_UUID()); visitor_id = getCookie("unique_visitor_id6"); } var referrer = document.referrer; var utm_params_url; let calendly_param = getAllUrlParams(); \$("#iksiteurl").val(iksite_url); if(calendly_param['invitee_first_name'] != undefined){ \$("#invitee_first_name").val(decodeURIComponent(calendly_param['invitee_first_name'])); \$("#invitee_last_name").val(decodeURIComponent(calendly_param['invitee_last_name'])); \$("#invitee_email").val(decodeURIComponent(calendly_param['invitee_email'])); \$("#answer_1").val(decodeURIComponent(calendly_param['answer_1'])); \$("#utm_source").val(decodeURIComponent(calendly_param['utm_source'])); \$("#utm_medium").val(decodeURIComponent(calendly_param['utm_medium'])); \$("#utm_campaign").val(decodeURIComponent(calendly_param['utm_campaign'])); \$("#salesforce_uuid").val(decodeURIComponent(calendly_param['salesforce_uuid'])); \$("#gclid").val(decodeURIComponent(calendly_param['gclid'])); \$("#msclkid").val(decodeURIComponent(calendly_param['msclkid'])); \$("#fbclid").val(decodeURIComponent(calendly_param['fbclid'])); \$("#event_start_time").val(decodeURIComponent(calendly_param['event_start_time'])); \$("#event_end_time").val(decodeURIComponent(calendly_param['event_end_time'])); \$("#user_id").val(visitor_id); utm_params_url = {}; } else{ utm_params_url = getAllUrlParams(); } if(utm_params_url['gh_jid'] != undefined){ utm_params_url = {}; \$('.careers-sec1, .careers-sec2, .careers-sec3, .careers-sec4').hide(); } let isEmpty = jQuery.isEmptyObject(utm_params_url); let r_visit = read_cookie("v_latest"); if(isEmpty && (r_visit == null)){ bake_organic_cookie(); } else if(!isEmpty && (r_visit == null)){ bake_cookie("v_latest", utm_params_url); if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1) bake_cookie_history("v_history", utm_params_url); } else if(isEmpty && (r_visit != null)){ if(r_visit['utm_source'] != "Organic") { bake_organic_cookie(); } } else{ if(!isDuplicateCookie(utm_params_url, r_visit)){ bake_cookie("v_latest", utm_params_url); if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1) bake_cookie_history("v_history", utm_params_url); } } function isCookieSizeExceeded(){ let c_size = 15; var h_cookie = read_cookie("v_history"); if (h_cookie == null) return; if(h_cookie.length >= c_size){ h_cookie.shift(); bake_cookie("v_history", h_cookie); } } function isDuplicateCookie(utm_params, recent_visit){ if((utm_params['utm_source'] == recent_visit['utm_source']) && (utm_params['utm_medium'] == recent_visit['utm_medium']) && (utm_params['utm_campaign'] == recent_visit['utm_campaign']) && (utm_params['utm_adset'] == recent_visit['utm_adset']) && (utm_params['utm_content'] == recent_visit['utm_content']) && (utm_params['utm_term'] == recent_visit['utm_term']) && (utm_params['fbclid'] == recent_visit['fbclid'])) { return true; } else{return false;} } function bake_cookie_history(name, value) { isCookieSizeExceeded(); var visits_history = []; var iksutmhistory = read_cookie(name); if(iksutmhistory == "" || iksutmhistory == null){ var utmstring = value; utmstring.timestamp = \$.now(); visits_history.push(utmstring); var cookie = [name, '=', JSON.stringify(visits_history), ';expires','=', expdate.toGMTString(), '; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } else { var result = document.cookie.match(new RegExp(name + '=([^;]+)')); result && (result = JSON.parse(result)); var newhistoryobj = result.push(value); var cookie = [name, '=', JSON.stringify(result), ';expires','=', expdate.toGMTString(), '; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } } function bake_organic_cookie(){ var organicobj = { "utm_source":"Organic", "utm_medium":"", "utm_campaign":"", "utm_adset":"", "utm_content":"", "utm_term":"", "timestamp":\$.now()}; if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1){ bake_cookie_history("v_history", organicobj); bake_cookie("v_latest", organicobj); } } function bake_cookie(name, value) { var utmstring = value; utmstring.timestamp = \$.now(); var cookie = [name, '=', JSON.stringify(utmstring), ';expires','=', expdate.toGMTString(),'; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } function read_cookie(name) { var result = document.cookie.match(new RegExp(name + '=([^;]+)')); result && (result = JSON.parse(result)); return result; } function setCookie(cname, cvalue) { var d = new Date(); d.setTime(d.getTime() + (365*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } \$('.calendly-link-widget').click(function(){ var active_visit = read_cookie("v_latest"); var visit_history = read_cookie("v_history"); var utm_medium_str=""; for (const property in active_visit) { if (`\${property}` == "utm_medium") { utm_medium_str = utm_medium_str + `\${active_visit[property]}`; } } utm_medium_str = utm_medium_str + ":"; for (const property in active_visit) { if (`\${property}` == "gclid") { utm_medium_str = utm_medium_str + "gclid:" + `\${active_visit[property]}`; } else if (`\${property}` == "msclkid") { utm_medium_str = utm_medium_str + "msclkid:" + `\${active_visit[property]}`; } else if (`\${property}` == "fbclid") { utm_medium_str = utm_medium_str + "fbclid:" + `\${active_visit[property]}`; } } if ( (utm_medium_str.indexOf("gclid") == -1) && (utm_medium_str.indexOf("msclkid") == -1) && (utm_medium_str.indexOf("fbclid") == -1)){ utm_medium_str = utm_medium_str + ":"; } utm_medium_str = utm_medium_str + ":" + visitor_id.toString().replace(/"/g, ""); var utm_campaign="",utm_source="",utm_content="",utm_term=""; for (const property in active_visit) { if (`\${property}` == "utm_campaign") { utm_campaign = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_source") { utm_source = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_content") { utm_content = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_term") { utm_term = `\${active_visit[property]}`; } } Calendly.initPopupWidget({ url: 'https://calendly.com/interviewkickstart/enrollment-workshop', utm: { utmCampaign: utm_campaign, utmSource: utm_source, utmMedium: utm_medium_str, utmContent: utm_content, utmTerm: utm_term } }); let page_url = window.location.pathname; var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } setTimeout(function(){ location.href = calendlyurl; }, 100); } }); return false; }); \$('.direct-link').click(function(e) { e.preventDefault(); calendlySignup(false,""); }); \$('.lpv5-home-form').click(function(e) { e.preventDefault(); var formstr = '&first_name=' + \$("#lpv5-fname").val() + '&last_name=' + \$("#lpv5-lname").val() + '&a1=' + \$("#lpv5-phone").val() + '&email=' + \$("#lpv5-email").val(); calendlySignup(true, formstr); }); \$('.request-info-close').click(function(e){ \$('.request-info-wrap').css("display","none"); \$('.request-info-wrap').css("opacity",0); }); \$('.btn-webinar-popup').click(function(e){ e.preventDefault(); \$('.request-info-wrap').css("display","flex"); \$('.request-info-wrap').css("opacity",1); let page_url = window.location.pathname; let visit_history = read_cookie("v_history"); var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } } }); }); \$('.form-to-calendly').click(function(e) { e.preventDefault(); var active_visit = read_cookie("v_latest"); var full_phone_number = int_phone.getNumber(intlTelInputUtils.numberFormat.E164); \$("input[name='phone_number[full]'").val(full_phone_number); var formstr = '&first_name=' + \$("#wcalendly-fname").val() + '&last_name=' + \$("#wcalendly-lname").val() + '&a1=' + full_phone_number + '&email=' + encodeURIComponent(\$("#wcalendly-email").val()) + '&salesforce_uuid=' + v_timezone; \$('#wc_utm_source').val(active_visit['utm_source']); \$('#wc_utm_medium').val(active_visit['utm_medium']); \$('#wc_utm_campaign').val(active_visit['utm_campaign']); \$('#wc_gclid').val(active_visit['gclid']); \$('#wc_msclkid').val(active_visit['msclkid']); \$('#wc_timezone').val(v_timezone); \$('#wc_page_url').val(window.location.pathname); \$('#wc_user_id').val(visitor_id); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#wcalendly-fname" ).keypress(function() { \$('.fname-error').addClass('hide'); }); \$( "#wcalendly-lname" ).keypress(function() { \$('.lname-error').addClass('hide'); }); \$( "#wcalendly_pnumber" ).keypress(function() { \$('.mobile-error').addClass('hide'); }); \$( "#wcalendly-email" ).keypress(function() { \$('.email-error').addClass('hide'); }); \$( "#wcalendly-fname, #wcalendly-lname, #wcalendly-email, #wcalendly_pnumber" ).focus(function() { \$('.fname-error, .lname-error, .email-error, .mobile-error').addClass('hide'); }); if( (\$("#wcalendly-fname").val().length == 0) && (\$("#wcalendly-lname").val().length == 0) && (\$("#wcalendly-email").val().length == 0) && (\$("#wcalendly_pnumber").val().length == 0)){ \$('.fname-error, .lname-error, .email-error, .mobile-error').removeClass('hide'); } else if (!name_regex.test(\$("#wcalendly-fname").val()) || \$("#wcalendly-fname").val().length == 0){ \$('.fname-error').removeClass('hide'); }else if (!name_regex.test(\$("#wcalendly-lname").val()) || \$("#wcalendly-lname").val().length == 0){ \$('.lname-error').removeClass('hide'); }else if (!email_regex.test(\$("#wcalendly-email").val()) || \$("#wcalendly-email").val().length == 0){ \$('.email-error').removeClass('hide'); }else if(!phone_regex.test(\$("#wcalendly_pnumber").val()) || \$("#wcalendly_pnumber").val().length == 0){ \$('.mobile-error').removeClass('hide'); }else{ \$(".leadcapturing-form").submit(); calendlySignup(true,formstr); } }); function calendlySignup(isthisForm,formstr) { \$('.loading-overlay').css('display', 'flex'); var calendlyurl = "https://calendly.com/interviewkickstart/enrollment-workshop?"; var active_visit = read_cookie("v_latest"); var visit_history = read_cookie("v_history"); var gaid = getCookie("_ga"); visitor_id = visitor_id + gaid; //console.log("visitor_id: "+visitor_id); var utm_medium_str = "utm_medium="; for (const property in active_visit) { if (`\${property}` == "utm_medium") { utm_medium_str = utm_medium_str + `\${active_visit[property]}`; } } utm_medium_str = utm_medium_str + ":"; for (const property in active_visit) { if (`\${property}` == "gclid") { utm_medium_str = utm_medium_str + "gclid:" + `\${active_visit[property]}`; } else if (`\${property}` == "msclkid") { utm_medium_str = utm_medium_str + "msclkid:" + `\${active_visit[property]}`; } else if (`\${property}` == "fbclid") { utm_medium_str = utm_medium_str + "fbclid:" + `\${active_visit[property]}`; } } if ( (utm_medium_str.indexOf("gclid") == -1) && (utm_medium_str.indexOf("msclkid") == -1) && (utm_medium_str.indexOf("fbclid") == -1)){ utm_medium_str = utm_medium_str + ":"; } utm_medium_str = utm_medium_str + ":" + visitor_id; for (const property in active_visit) { var ptyn = `\${active_visit[property]}`; if( (`\${property}` != "utm_medium") && (`\${property}` != "msclkid") && (`\${property}` != "fbclid") && (`\${property}` != "gclid") ){ calendlyurl = calendlyurl+`\${property}`+"="+`\${active_visit[property]}`+"&"; } } utm_medium_str = utm_medium_str + "&salesforce_uuid="+v_timezone; calendlyurl = calendlyurl + utm_medium_str; if(isthisForm){ calendlyurl = calendlyurl + formstr; } let page_url = window.location.pathname; var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } setTimeout(function(){ location.href = calendlyurl; \$('.loading-overlay').css('display', 'none'); }, 100); } }); } window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-54935903-1', { 'user_id': visitor_id }); \$(document).ready(function () { \$('.btn-sendinblue-subscribe').click(function(e) { e.preventDefault(); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; //var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#sb-fname" ).keypress(function() { \$('.fname-sb-error').addClass('hide'); }); \$( "#sb-email" ).keypress(function() { \$('.email-sb-error').addClass('hide'); }); \$( "#sb-fname, #sb-email" ).focus(function() { \$('.fname-sb-error, .email-sb-error').addClass('hide'); }); if( (\$("#sb-fname").val().length == 0) && (\$("#sb-email").val().length == 0)){ \$('.fname-sb-error, .email-sb-error').removeClass('hide'); } else if (!name_regex.test(\$("#sb-fname").val()) || \$("#sb-fname").val().length == 0){ \$('.fname-sb-error').removeClass('hide'); }else if (!email_regex.test(\$("#sb-email").val()) || \$("#sb-email").val().length == 0){ \$('.email-sb-error').removeClass('hide'); }else{ \$("#form-sendinblue-popup").submit(); setTimeout(function(){ \$('.close-sb-popup').trigger('click'); \$('.subscription-popup').css('right','-400px'); }, 2000); } }); }); idleTimer = null; idleState = false; idleWait = 300000; (function (\$) { \$(document).ready(function () { \$('.nudge-blog').click(function(e) { e.preventDefault(); fbq('track', 'nudge_blog'); window.open(\$(this).attr('href')); }); \$('*').bind('mousemove keydown scroll', function () { clearTimeout(idleTimer); idleState = false; idleTimer = setTimeout(function () { bioEp.showPopup(); idleState = true; }, idleWait); }); \$("body").trigger("mousemove"); }); }) (jQuery) \$( document ).ready(function() { let utm_sendinblue = getAllUrlParams(); \$(".sb_utm_source").val((utm_sendinblue['utm_source'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_source'])); \$(".sb_utm_medium").val((utm_sendinblue['utm_medium'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_medium'])); \$(".sb_utm_campaign").val((utm_sendinblue['utm_campaign'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_campaign'])); \$(".sb_utm_term").val((utm_sendinblue['utm_term'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_term'])); \$(".sb_utm_content").val((utm_sendinblue['utm_content'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_content'])); \$(".sb_page_url").val(decodeURIComponent(window.location.pathname)); \$('a').each(function() { var reg_exp = new RegExp('/' + window.location.host + '/'); if (!reg_exp.test(this.href)) { // External Link Found \$(this).attr('rel','nofollow'); } }); }); var usertimezone; function geoip(json){ usertimezone = json.timezone; } \$(document).ready(function() { var ltz = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join(''); \$('.webinar-slots-item').each(function(){ let localtime = UTLtoLocal(\$(this).find('.utc-date').val(), \$(this).find('.utc-date').data('timezone')); \$(this).find('.slot-radio-date').html(localtime +" "+ltz); \$(this).find('.utc-date').data('local',localtime); if(compareDates(localtime)){ //console.log("Registrations Closed for: "+ localtime); \$(this).hide(); } }); function UTLtoLocal(utcdate, timezone) { let pdtdate = new Date(utcdate); // pdtdate.setHours(pdtdate.getHours() - 1); let theDate = new Date(Date.parse(pdtdate + timezone)); let localDate = theDate.toLocaleDateString('en-US', { weekday: 'short', month: 'long', day: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); return localDate; } function compareDates(eventdate){ let currentdate = new Date(); let edate = new Date(eventdate); if(currentdate.getTime() >= edate.getTime()){ return true; } } int_phone = window.intlTelInput(document.querySelector("#wcalendly_pnumber"), { initialCountry: "auto", geoIpLookup: function(callback) { \$.get('https://get.geojs.io/v1/ip/geo.js', function() {}, "jsonp").always(function(resp) { var countryCode = (resp && resp.country_code) ? resp.country_code : "us"; callback(countryCode); }); }, hiddenInput: "full", utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js" }); \$('.btn-submit-wc-step1').click(function(e) { e.preventDefault(); let active_visit = read_cookie("v_latest"); var full_phone_number = int_phone.getNumber(intlTelInputUtils.numberFormat.E164); \$("input[name='phone_number[full]'").val(full_phone_number); \$('.wc_utm_source').val(active_visit['utm_source']); \$('.wc_utm_medium').val(active_visit['utm_medium']); \$('.wc_utm_campaign').val(active_visit['utm_campaign']); \$('.wc_utm_term').val(active_visit['utm_term']); \$('.wc_utm_content').val(active_visit['utm_content']); \$('.wc_fbclid').val(active_visit['gclid']); \$('.wc_gclid').val(active_visit['gclid']); \$('.wc_msclkid').val(active_visit['msclkid']); \$('.wc_timezone').val(usertimezone); \$('.wc_page_url').val(window.location.pathname); \$('.wc_user_id').val(visitor_id); \$('.wc_hostname').val(window.location.hostname); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#wcalendly-fname" ).keypress(function() { \$('.fname-error').addClass('hide'); }); \$( "#wcalendly-lname" ).keypress(function() { \$('.lname-error').addClass('hide'); }); \$( "#wcalendly_pnumber" ).keypress(function() { \$('.mobile-error').addClass('hide'); }); \$( "#wcalendly-email" ).keypress(function() { \$('.email-error').addClass('hide'); }); \$( "#wcalendly-fname, #wcalendly-lname, #wcalendly-email, #wcalendly_pnumber" ).focus(function() { \$('.fname-error, .lname-error, .email-error, .mobile-error').addClass('hide'); }); if( (\$("#wcalendly-fname").val().length == 0) && (\$("#wcalendly-lname").val().length == 0) && (\$("#wcalendly-email").val().length == 0) && (\$("#wcalendly_pnumber").val().length == 0)){ \$('.fname-error, .lname-error, .email-error, .mobile-error').removeClass('hide'); } else if (!name_regex.test(\$("#wcalendly-fname").val()) || \$("#wcalendly-fname").val().length == 0){ \$('.fname-error').removeClass('hide'); }else if (!name_regex.test(\$("#wcalendly-lname").val()) || \$("#wcalendly-lname").val().length == 0){ \$('.lname-error').removeClass('hide'); }else if (!email_regex.test(\$("#wcalendly-email").val()) || \$("#wcalendly-email").val().length == 0){ \$('.email-error').removeClass('hide'); }else if(!phone_regex.test(\$("#wcalendly_pnumber").val()) || \$("#wcalendly_pnumber").val().length == 0){ \$('.mobile-error').removeClass('hide'); }else{ \$('.wc_fname').val(\$("#wcalendly-fname").val()); \$('.wc_lname').val(\$("#wcalendly-lname").val()); \$('.wc_email').val(\$("#wcalendly-email").val()); \$('.wc_phone').val(full_phone_number); \$(".lead-form-details").hide(); \$(".lead-form-moredetails").show(); \$("#dlc-personal-details").submit(); } }); \$( "input[type=radio]" ).on( "click", function() { \$('.slots-error').addClass('hide'); \$('.wc_webinar_starttime').val(\$( this ).data('starttime')); \$('.wc_webinar_endtime').val(\$( this ).data('endtime')); \$(".slot-booked2").text(\$(this).data('local')); }); \$('.btn-bookthis-slot').click(function(e) { e.preventDefault(); let n = \$( "input:checked" ).length; if( n == 0){ \$('.slots-error').removeClass('hide'); }else{ \$('.wc_slot').val(\$( "input:checked" ).val()); \$('.slots-error').addClass('hide'); \$(".lead-form-slots").hide(); \$(".lead-form-details").show(); \$("#dlc-webinar-slots").submit(); } }); }); ```