Algorithm design and analysis on computer problem mergesort

Source: Internet
Author: User

#include <iostream>
using namespace Std;

#define N 100

int g_array[n]; Store the input number
static int count; Number of elements to store

initialization function
void Initial ()
{
cout << "Please enter the number of elements:";
Cin >> Count;
cout << "Please enter" << count << "elements:";
for (int i = 0; i < count; i + +)
{
CIN >> G_array[i];
}
}

//merge function
void merge (int a[], int l, int m, int r)
{
    int i = l, j = m+1, k = l;
    int b[n];
    while (i <= m && J <= R)
    {
         if (A[i] <= a[j])
        {
             b[k++] = a[i++];
       }
        Else
        {
             b[k++] = a[j++];
       }
   }

if (i > M)
{
for (int p = j; p <= r; p + +)
{
b[k++] = a[p];
}
}
Else
{
for (int p = i; P <= m; p + +)
{
b[k++] = a[p];
}
}

Copy the elements in b[] into a[]
for (int q = l; q <= r; q + +)
{
A[Q] = B[q];
}
}

Recursive algorithm representation of merge sort
void Bottomupsort (int a[], int left, int. right)
{
if (left < right)//array must have at least two elements
{
int i = (right + left)/2;
Bottomupsort (A, left, I);
Bottomupsort (A, i+1, right);
Merge (A, left, I, right); Sort the elements left to right
}
}

Print a sorted array
void Print ()
{
cout << "after Bottomupsort:";
for (int i = 0; i < count; i + +)
{
cout << G_array[i] << "";
}
cout << Endl;
}

int main ()
{
Initial ();
if (Count > 1)
{
Bottomupsort (G_array, 0, count-1);
Print ();
}
else if (count = = 1)
{
Print ();
}
System ("pause");
return 0;
}

Algorithm design and analysis on computer problem mergesort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.