Sorting
Sorting
SORTING
• (selection sort)SELECTION(A,N)
• This algorithm sorts the array A with N Elements.
• 1- repeat step 2 and 3 for k=1,2,…,N-1
• 2- call MIN(A,K,N,LOC)
• 3- Interchange A[k] and A[LOC]
• [end of step 1loop]
• 4- Exit.
INSERTION SORT
Pass A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
K=1 -∞ 77 33 44 11 88 22 66 55
K=2 -∞ 77 33 44 11 88 22 66 55
K=3 -∞ 33 77 44 11 88 22 66 55
K=4 -∞ 33 44 77 11 88 22 66 55
K=5 -∞ 11 33 44 77 88 22 66 55
K=6 -∞ 11 33 44 77 88 22 66 55
K=7 -∞ 11 22 33 44 77 88 66 55
K=8 -∞ 11 22 33 44 66 77 88 55
Sorted -∞ 11 22 33 44 55 66 77 88
INSERTION ALGORITHM
• (insertion Sort)INSERTION(A,N)
• This algorithm sort the array A with N elements.
• 1. repeat step 2 to 4 for k=1,2,3,….,N
• 2. Set TEMP=A[k] and PTR=K-1
• 3. Repeat while TEMP<A[PTR]
• a) Set A[PTR+1]=A[PTR]
• b) Set PTR=PTR-1
• [end of loop]
4. Set A[PTR+1]=TEMP [insert element in proper
place]
5. [end of step 1 loop]
6. Return
MERGING
-44 4 0 56 3 -6 23 8 28 1
-44 4 0 28 3 -6 23 8 56 1
-44 4 0 28 1 -6 23 8 56 3
New gap value => 5/1.3 = 3;
-44 1 0 28 4 -6 23 8 56 3
-44 1 -6 28 4 0 23 8 56 3
-44 1 -6 23 4 0 28 8 56 3
-44 1 -6 23 4 0 3 8 56 28