- #1
evinda
Gold Member
MHB
- 3,836
- 0
Hello! (Wave)
I am looking at the algorithm of the Insertion Sort:
Input: $A[1 \dots n]$ $\leftrightarrow$ a sequence of $n$ numbers
I want to calculate the cost of this algorithm. I thought that I could do I do it like that:
The "for" loop runs $n-2+1=n-1$ times, there are $3$ commands: key<-A[j],j<-j-1, A[i+1]<-key,the "while" loops run at most $n-1$ times and in the "while" loop,there are 2 commands: A[i+1]<-A,i<-i-1.
So,the cost is: $3(n-1)+2(n-1)=5n-5=5(n-1)= O(n)$
Could you tell me if it is right or if I have done something wrong? (Thinking)(Worried)
I am looking at the algorithm of the Insertion Sort:
Input: $A[1 \dots n]$ $\leftrightarrow$ a sequence of $n$ numbers
Code:
for j<-2 to n
key<-A[j]
i<-j-1
while (i>0 and A[i]>key)
A[i+1]<-A[i]
i<-i-1
end
A[i+1]<-key
end
I want to calculate the cost of this algorithm. I thought that I could do I do it like that:
The "for" loop runs $n-2+1=n-1$ times, there are $3$ commands: key<-A[j],j<-j-1, A[i+1]<-key,the "while" loops run at most $n-1$ times and in the "while" loop,there are 2 commands: A[i+1]<-A,i<-i-1.
So,the cost is: $3(n-1)+2(n-1)=5n-5=5(n-1)= O(n)$
Could you tell me if it is right or if I have done something wrong? (Thinking)(Worried)