Answer to Question #278611 in C++ for zain

Question #278611

Programming Problem 

you are required to solve all the sorting algorithms up to mergesort mentioned in slides for both array as well as linked list.in c++.

Array vs linked list

Already covered

Bubble sort

Selection sort

Insertion sort

Merge sort


1
Expert's answer
2021-12-13T00:02:31-0500
void mergeSort(int arr[], int p, int q, int r) {
    int n1 = q - p + 1;
    int n2 = r - q;


    int L[n1], M[n2];


    for (int i = 0; i < n1; i++)
        L[i] = arr[p + i];
    for (int j = 0; j < n2; j++)
        M[j] = arr[q + 1 + j];


    int i, j, k;
    i = 0;
    j = 0;
    k = p;


    while (i < n1 && j < n2) {
        if (L[i] <= M[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = M[j];
            j++;
        }
        k++;
    }


    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }


    while (j < n2) {
        arr[k] = M[j];
        j++;
        k++;
    }
}


void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}


void bubbleSort(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n-1; i++)    
     
    for (j = 0; j < n-i-1; j++)
        if (arr[j] > arr[j+1])
            swap(&arr[j], &arr[j+1]);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog