Sorting Algorithms
BUBBLE SORT INSERTION SORT SELECTION SORT RADIX SORT
TOPICS TO BE DISCUSSED
BUBBLE SORT If we compare pairs of adjacent elements
and none are out of order, the list is sorted
If any are out of order, we must have to swap them to get an ordered list
Bubble sort will make passes though the list swapping any adjacent elements that are out of order
7 2 8 5 4
2 7 8 5 4
2 7 8 5 4
2 7 5 8 4
2 7 5 4 8
2 7 5 4 8
2 5 7 4 8
2 5 4 7 8
2 7 5 4 8
2 5 4 7 8
2 4 5 7 8
2 5 4 7 8
2 4 5 7 8
2 4 5 7 8
(done)
EXAMPLE OF BUBBLE SORT
ALGORITHM……
STEP 1: Repeat steps 2 and 3 for I=1 to N-1STEP 2: Repeat step 3 for J=1 to N-1STEP 3: [Exchange elements] If A[J]>A[J+1] then TEMP:=[J] A[J]:=A[J+1] A[J+1]:=TEMP [end of if statement] [end of step 2 for statement] [end of step 1 for statement]STEP 4: Exit
INSERTION SORT
ALGORITHM……STEP 1: Repeat step 2 to 4 for I=2 to nSTEP 2: Set temp:=A[I] position:=I-1
STEP 3: [move down 1 position all elements greater than temp]
repeat while temp<A[position] and position>=1 set A[position +1]:=A[position] set position:=position-1 [end of loop]STEP 4: [insert temp at proper position] set A[position+1]:=temp [end of step 1 for loop]STEP 5: [finished] Exit
SELECTION SORT
ALGORITHM……STEP 1: repeat steps 2 to 4 for K=1 to n-1STEP 2: set min:=A[K] position:=K
STEP 3:[make pass and obtain element with smallest value] Repeat for I=K+1 To n if min>A[I] then min:=A[I] and position:=1 [end of if statement] [end of step 3 loop]STEP 4:[exchange elements] if position <> K then temp:=A[k] A[K]:=A[position] A[position]:=temp [end of if statement] [end of step 1 for loop]STEP 5:[finished] exit
RADIX SORT
Assuming decimal elements and 10 buckets, we would put the elements into the bucket associated with its units digit
The buckets are actually queues so the elements are added at the end of the bucket
At the end of the pass, the buckets are combined in increasing order
RADIX SORT EXAMPLE
The unit digit is 0
The unit digit is 1
The unit digit is 2
The unit digit is 3
RADIX SORT EXAMPLE(CONTINUED)The unit digits are already in order
Now start sorting the tens digit
Values in the buckets are now in order
The unit and tens digits are already in order
Now start sorting the hundreds digit
RADIX SORT EXAMPLE(CONTINUED)
THANKS