Your New Mentor

+ how to merge sort in C

This week we’re rolling out our newest tool: Mentor. We’re also sharing a guide on merge sorting in C, resources for those interested in earning tech certifications, and this year’s best artificial intelligence courses.

This Week’s Resources

Your Tech Mentor

Tell it what you want, and it will help you reach your goals. Looking for a cybersecurity job? It can point out the latest opportunities. Need to learn web development? It will show the community’s top-rated tutorials. It’s free, made especially for the community at hackr.io.

This Week’s Jobs

Here are a few of the latest job opportunities in tech. These are all posted on the hackr job board, which is updated daily.

How to Merge Sort in C

Here’s an excerpt from our guide on how to merge sort in C.

Merge sort is one of the most powerful sorting algorithms, widely used in various applications. The best part about this algorithm is that it sorts a given data in O(n log n) complexity, as opposed to O(n²) complexity of bubble sort and selection sort.

Moreover, the function mergesort is super interesting as it’s a classic case study for one of the most widely used techniques in Computer Science - divide and conquer.

Not to mention, it’s a favorite for coding interviews, so it’s always helpful to have the basics of mergesort in your coding arsenal.

Steps to Sort an Array Using Merge Sort

  • Divide the array into two parts of lengths n/2 and n - n/2 respectively (if n is odd, round off the value of n/2). Let us call these arrays as left half and right half respectively.

  • Recursively sort the left half array and the right half array.

  • Merge the left half array and right half array to get the full array sorted.

void merge_sort(int i, int j, int a[], int aux[]) {
    if (j <= i) {
        return;
    }

    int mid = (i + j) / 2;
    merge_sort(i, mid, a, aux);
    merge_sort(mid + 1, j, a, aux);

    int pointer_left = i;
    int pointer_right = mid + 1;
    int k;

    // Merge the two halves
    for (k = i; k <= j; k++) {
        if (pointer_left > mid) {
            aux[k] = a[pointer_right++];
        } else if (pointer_right > j) {
            aux[k] = a[pointer_left++];
        } else if (a[pointer_left] <= a[pointer_right]) {
            aux[k] = a[pointer_left++];
        } else {
            aux[k] = a[pointer_right++];
        }
    }

    // Copy the sorted elements back to the original array
    for (k = i; k <= j; k++) {
        a[k] = aux[k];
    }
}

Artificial Intelligence Courses

Ready to bring AI into your workplace? Here are this year’s best artificial intelligence courses. We evaluated programs from world-class institutions and free online courses to find the best options for this year.

Additional Reading

Rate this Newsletter

The team at Hackr.io aims to provide the best information possible. Please let us know how we're doing!

Login or Subscribe to participate in polls.