Introduction to Algorithms 2.1-2.3 Partial Answers

Exercise 2.1.2

#include <iostream>

using namespace std;
void insectionSort(int a[],int len)
{
    for(int i=1;i<len;i++)
    {
        int j=i-1;
        int t=a[i];
        while(t>a[j]&&j>=0)//Use t to compare instead of a[i] because a[i] will change
        {
            a[j+1]=a[j];
            j--;
        }
        a[j+1]=t;
    }
}
intmain()
{
    int a[7]={41,25,89,74,32,14,258};
    insectionSort(a,7);
    for(int i=0;i<7;i++)
    {
        cout<<a[i]<<" ";
    }
    return 0;
}

2.1.4 

#include <iostream>

using namespace std;
  
int* add(int a[],int b[],int n)
{
    int* c=new int(n+1);
    int t;
    for(int i=n-1;i>=0;i--)
    {
        c[i]=a[i]+b[i];//The original c of new has value
    }
    for(int i=n-1;i>=1;i--)
    {
        if(c[i]==2)
        {
            c[i-1]++;
            c[i]=c[i]%2;
        }
    }
    if(c[0]==2) c[0]=0;

    return c;

}
intmain()
{
   int a[3]={1,0,1};
   int b[3]={0,1,1};
   int *c=add(a,b,3);
   for(int i=0;i<3;i++)
    cout<<c[i];
   delete[] c;
    return 0;
}

2.2.2

void selectSort(int& a[],int len)
{
    for(int i=0;i<len;i++)//n=len;
    {
        int t,max=-9999999;
        for(int j=i+1;j<len;j++)//1~len的和+1
        {
            if(a[j]>max) //The sum of 1~len
            {
                max=a[j];       
                t=j;
            }
        }
        swap(a[i],a[t]); //len
        
    }
    //Total time 3*len*(len-1)/2+1~len sum +1+len+len
    // on^2 no distinction between best and worst
}

2.2.3 

Linear search

Average case (n+1)/2 on

The average number of times is (n+1)/2, not n/2.
If the number to be searched is the first number, it is necessary to compare the first number with the number to be searched for once.
If the number to be searched is the second number, you need to compare the first number, the second number and the number to be searched, and compare twice.
...
The number to be searched is the nth number, then the first number, the second number, ..., the nth number and the number to be searched need to be compared, and the comparison is n times.

The average number of times is (1+2+...+n)/n=(n+1)/2.

worst case on

2.3-4 Recursion of Insertion Sort

void insectionSort(int a[],int len)
{
    if(len==1) return;
    insectionSort(a,len-1);
        int t = a [len-1];
        int j=len-2;
        while(t>a[j]&&j>=0)
        {
            a[j+1]=a[j];
            j--;
        }
        a[j+1]=t;
    
}

T(n)=T(n-1)+on


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805518&siteId=291194637