2. Sorting
Four algorithms are described
1. Selection sort
2. Bubble sort
3. Insertion Sort
4. Merge Sort (Assignment)
3. Selection Sort
In the first pass, each item in the list is
compared with the first item in the list
If the first item in the list is bigger then the
item being compared then they are swapped.
26. Selection Sort Algorithm
Step 1. [Starting Selection Loop]
Repeat step 2 For S=1 to N-1 by 1
Step 2. [Starting Selection Loop]
Repeat step 3 For C=S+1 to N by 1
Step 3. [Compare Element]
If(A[s]> A[c]) Then
Temp=A[S]
A[S]=A[C]
A[S]=Temp
Exit
27. Bubble Sort
Bubble sort is a simple algorithm that
repeatedly steps through the list, compares
adjacent pairs and swap them if they are in
wrong order. The pass through the list is
repeated until list is sorted.
44. Bubble sort
5 7 6 1 8 2 0 3 4 9
Notice… we are sorting list into an ascending list. The largest number is now
at the end of the list…where it should be!
This completes the first pass through the list.
45. Bubble sort
5 7 6 1 8 2 0 3 4 9
The process begins again.
1st Comparison Second Pass
52. Bubble Sort
Write an algorithm to sort an array A consisting of
N elements in ascending order using bubble sort
Suppose variable U represents the control variable
for upper loop to control the number of iteration .
Similarly , variable I represent the control variable
for inner loop that scans the array starting from
element A[1] to A[U]
53. Cont.……
1. Set U=N
2. [Upper loop]
Repeat step 3 to 7 while (U>=1)
3. Set I=1
4. [Inner Loop]
Repeat step 5 to 6 while (I<=U)
5. IF A[I]>A[I+1]
T=A[I]
A[I]=A[I+1]
A[I+1]=T END IF
6. I=I+1
7. U=U-1
8. EXIT
54. Insertion Sort
In insertion sort algorithm, compare the value
until all the previous value is lesser than
compared value. Insertion sort is more
efficient than bubble sort because in insertion
sort the elements comparisons are lesser as
compared to bubble sort. Insertion sort is
suitable for small data.
56. Algorithm for insertion sort
Write an algorithm to sort an array A
consisting of N elements in ascending order
using Insertion sort method
Suppose variable U represents the control
variable for upper loop to control the number
of iteration . Similarly , variable I represent
the control variable for inner loop that scans
the array starting from element A[1] to A[U]
57. CONT.….
1. REPEAT STEP 2 TO 6 FOR C=1 TO N
2. TEMP=A[C]
3. L=C
4. REPEAT STEP 3 to 7 WHILE (L>0 AND TEMP<A[L-1])
5. A[L]=A[L-1] [END OF STEP 4 INNER LOOP]
6. A[L]=TEMP [INSERT VALUE]
[END OF STEP 1 UPPER LOOP]
7. EXIT