Sorting Algorithm (Group 3)
Sorting Algorithm (Group 3)
ALGORITHM
PRESENTED BY GROUP 3
z
What is Sorting?
Sorting refers to arranging data in a
particular format. Sorting algorithm specifies
the way to arrange data in a particular order.
Most common orders are in numerical or
lexicographical order.
z
There are two different categories in
sorting:
• BUBBLE SORTING
• MERGE SORTING
• QUICK SORTING
z
WHAT IS BUBBLE SORTING?
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first
two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are
already in order (8 > 5), algorithm does not swap them.
z
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
1.
2.
z
This does not change the sequence of appearance of items
in the original. Now we divide these two arrays into halves.
2.
3.
z
We further divide these arrays and we achieve atomic value which
can no more be divided.
3.
4.
z
4.
5.
z
In the next iteration of the combining phase, we
compare lists of two data values, and merge them
into a list of found data values placing all in a sorted
order.
5.
6.
z
After the final merging, the list should look
like this:
6.
7.
z
WHAT IS QUICK SORTING?
1. Find a “pivot” item in the array. This item is the basis for
comparison for a single round.
2. Start a pointer (the left pointer) at the first item in the array.
3. Start a pointer (the right pointer) at the last item in the array.
4. While the value at the left pointer in the array is less than the
pivot value, move the left pointer to the right (add 1). Continue until
the value at the left pointer is greater than or equal to the pivot
value.
z
Quick Sort Algorithm: Steps on how it works:
5. While the value at the right pointer in the array is greater than the pivot value,
move the right pointer to the left (subtract 1). Continue until the value at the right
pointer is less than or equal to the pivot value.
6. If the left pointer is less than or equal to the right pointer, then swap the values
at these locations in the array.
7. Move the left pointer to the right by one and the right pointer to the left by one.