Algo Cha 5
Algo Cha 5
Algo Cha 5
We change our low to mid + 1 and find the new mid value again.
newlow = mid + 1=4+1=5
mid = (newlow + upper) / 2
mid=5+9/2=7.5
Our new mid is 7 now. We compare the value stored at location 7 with
our target value 31.
Cont..
• The value stored at location 7 is not a match, rather it is more than
what we are looking for. So, the value must be in the lower part
from this location.Hence, we calculate the mid again. This time it is
5. if A[midPoint] > x
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 (done)
2 7 5 8 4 2 5 4 7 8
2 7 5 4 8
Cont..
1. Input n numbers of an array A
2. Initialize i = 0 and repeat through step 4 if (i < n-1)
3. Initialize j = 0 and repeat through step 4 if (j < n – i – 1)
4. If (A[j] > A[j + 1])
(a) Swap = A[j]
(b) A[j] = A[j + 1]
(c) A[j + 1] = Swap
5. Display the sorted numbers of array A
6. Exit.
Cont..
Implementation:
void bubble_sort(list[])
{
int i,j,temp;
for(i=0;i<n; i++){
for(j=n-1;j>i; j--){
if(list[j]<list[j-1]){
temp=list[j];
list[j]=list[j-1];
list[j-1]=temp;
}//swap adjacent elements
}//end of inner loop
}//end of outer loop
}//end of bubble_sort
II. Selection Sort: Idea
To repetitively pick up the smallest element from unsorted group and
put it to sorted one.
Selection sort algorithm finds the smallest element of the array and
interchanges it with the element in the first position of the array. Then
it finds the second smallest element from the remaining elements in
the array and places it in the second position of the array and so on…
1. We have two group of items: sorted group, and unsorted group
2. Initially, all items are in the unsorted group. The sorted group is
empty.
Basic Idea:
1. Loop through the array from i=0 to n-1.
2. Select the smallest element in the array from i to n
3. Swap this value with value at position i.
Algorithm
1. Select the “best” (eg. smallest) item from the unsorted group,
then put the “best” item at the end of the sorted group.
2. Repeat the process until the unsorted group becomes empty.
• Let A be a linear array of ‘n’ numbers, A [1], A [2], A [3],...... A
[n].
Step 1: Find the smallest element in the array of n numbers A[1],
A[2], ...... A[n]. Let LOC is the location of the smallest number in the
array. Then interchange A[LOC] and A[1] by swap = A[LOC];
A[LOC] = A[1]; A[1] = Swap.
Step 2: Find the second smallest number in the sub list of n – 1
elements A [2] A [3] ...... A [n – 1] (first element is already sorted).
Now we concentrate on the rest of the elements in the array. Again A
[LOC] is the smallest element in the remaining array and LOC the
corresponding location then interchange A [LOC] and A [2].Now A
[1] and A [2] is sorted, since A [1] less than or equal to A [2].
Cont..
Step 3: Repeat the process by reducing one element each from the array
Selection Sort pick largest element
5 1 3 4 6 2
5 1 3 4 6 2
Selection Sort
5 1 3 4 2 6
Comparison
Data Movement
Sorted
5 1 3 4 2 6
Largest
2 1 3 4 5 6
Selection Sort
2 1 3 4 5 6
Comparison
Largest
Data Movement
Sorted
2 1 3 4 5 6
Largest
Selection Sort
2 1 3 4 5 6
Largest Comparison
Data Movement
Sorted
1 2 3 4 5 6
Selection Sort
1 2 3 4 5 6
DONE!
Implementation
void selectionSort(int list[ ] ) {
int minIndex, temp;
for (int i = 0; i <= n - 2; i++) {
minIndex = i;
for (j = i + 1; j <= n-1; j++)
if (list[j] < list[minIndex])
minIndex = j;
if (minIndex != i) {
temp = list[i];
list[i] = list[minIndex];
list[minIndex] = temp;
}}}
Algorithm selection sort
1. Input n numbers of an array A
2. Initialize i = 0
smallest=i
3. Initialize j = i + 1
4. if ( a[smallest}>a[j]])
(a) smallest=j
5. if (smallest! = i)
(a) swap = a[i]
(b) a[i] = a[smallest]
(c) a[smallest] = swap
6. display “the sorted numbers of array A”
7.exit
III. INSERTION SORT
• Insertion sort algorithm sorts a set of values by inserting
values into an existing sorted file. Compare the second
element with first, if the first element is greater than
second, place it before the first one. Otherwise place is
just after the first one. Compare the third value with
second. If the third value is greater than the second value
then place.
• It just after the second. Otherwise place the second value
to the third place. And compare third value with the first
value. If the third value is greater than the first value place
the third value to second place, otherwise place the first
value to second place. And place the third value to first
place and so on.
Cont..
1. The left most value can be said to be sorted relative to itself.
Thus, we don’t need to do anything.
2. Check to see if the second value is smaller than the first one.
If it is, swap these two values. The first two values are now
relatively sorted.
3. Next, we need to insert the third value in to the relatively
sorted portion so that after insertion, the portion will still be
relatively sorted.
4. Remove the third value first. Slide the second value to make
room for insertion. Insert the value in the appropriate
position.
5. Now the first three are relatively sorted.
6. Do the same for the remaining items in the list.
Algorithm for insertion sort
1. Input an array A of n numbers
2. Initialize j = 1 and repeat
through steps 4 If (j < n )
(a) Swap = A [j],
3. Initialize i = j – 1 Repeat the
step 3 if (Swap < A[i] and (i>= 0))
(a) A [i+1] = A [i]
(b) i = i-1
4. A [i +1] = Swap
5. Exit
Cont..
• This is an in-place comparison-based sorting algorithm. Here, a sub-
list is maintained which is always sorted.
• For example, the lower part of an array is maintained to be sorted.
An element which is to be 'insert'ed in this sorted sub-list, has to find
its appropriate place and then it has to be inserted there.
• Hence the name, insertion sort. The array is searched sequentially
and unsorted items are moved and inserted into the sorted sub-list (in
the same array).
• This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο(n2), where n is the number of items.
• How Insertion Sort Works?
We take an unsorted array for our example.
It finds that both 14 and 33 are already in ascending order. For now,
14 is in sorted sub-list.
Cont.
• Insertion sort moves ahead and compares 33 with 27.
It swaps 33 with 27. It also checks with all the elements of sorted sub-
list. Here we see that the sorted sub-list has only one element 14, and
27 is greater than 14. Hence, the sorted sub-list remains sorted after
swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares
33 with 10.
So we swap them.
Example:
int testfunc1( int num)
{if (num == 0)
return 0;
Else return (testfunc2(num-1));
}
int testfunc2(int num2)
{ return testfunc1( num2-1); }
Cont..
Write program to print numbers from 1 to 10when number is odd add 1
when number is even subtract 1.
Void odd()
Void even()
Int n=1
Void odd(){ void even()
If(n<=10) if(n<=10)
{ {
Cout<<n+1; cout<<n-1;
N++ n++;
Even(); odd();
}return ;} }return;}
Output=2,1,4,3,5,8,7.10,9
3. Nested Recursive Methods
• Nested recursion occurs when a method is not only defined in
terms of itself; but it is also used as one of the parameters :
Example:
int fun(int n) fun(96) ----fun(107) fun(97)
{ : : :
If(n>100) False true false
Return n-10; =97
else
Else return fun(fun(n+11));it become(fun(fun(107)===fun(fun(108)
}
let fun(95)
95>100F so fun(95+11)
Fun(106)
106>100;true;
N-10
106-10=96……
4. Tail and Non-Tail Recursive Methods
A method is tail recursive if in each of its recursive cases it executes
one recursive call and if there are no pending operations after that call.
Example 1:F(3) void f1(int n){
cout<<n <<" ";
Output 3,2,1 if(n > 0)
f1(n - 1);
}
Tail recursive method has the recursive call as the last statement in
the function. Non-Tail Recursive Methods
Example of non-tail recursive methods: if the recursive call is not last
thing done by function after returning back there is something left to
evaluate. After each recursive call there is a pending cout<<n <<" ";
Note the “pending operation” (namely the multiplication) to be performed on return
from each recursive call void f4(int n){
• Example 1: if f(3) if (n > 0)
f4(n - 1);
• Output 1,2,3 cout<<n <<" ";
}
Cont..
Reading assignment one and understand more
detail about
A. Tree Recursive Methods
B. Excessive Recursion(Fibonacci )
Summarize
Bubble sort - is a simple and stable sorting algorithm which
can be used to sort a small number of items.
• Algorithm's best-case complexity is O(n).
• Algorithm's worst-case complexity is O(n2).
• Algorithm's average-case complexity is O(n2).
Insertion sort - is a simple and stable sorting algorithm that
is relatively efficient for small lists and mostly sorted lists.
• Algorithm's best-case complexity is O(n).
• Algorithm's worst-case complexity is O(n2).
• Algorithm's average-case complexity is O(n2).
Cont..
Selection sort - is not a stable sorting algorithm, inefficient for large
lists . Algorithm's best-case complexity is O(n2).
• Algorithm's worst-case complexity is O(n2).
• Algorithm's average-case complexity is O(n2).
Time complexity linear search
In the best case, f (n) = O(1)
So in best case the order of time complexity for linear search is.
O(1)
worst case f (n) = (n)= O(n)
In the Average case, then f (n) = [(n/2].=O(n)
Binary search
Best case - O (1) comparisons
Worst case - O (log n) comparsions
Average case - O (log n) comparsions