Royal University of Phnom Penh
Faculty of Engineering
Data Structures and Algorithms
Chapter 1
Introducing Data Structures and Algorithms
DR. SRUN SOVILA
Outline
2
Arrays
Ordered Arrays
The Bubble Sort
The Insertion Sort
Outline
3
Arrays
Ordered Arrays
The Bubble Sort
The Insertion Sort
Bubble Sort1
4
For what sorting?
Arrange names in alphabetical order, students by grade,
customers by zip code,…
Sorting data is a preliminary step to search; E.g. applied
Binary search to sorted data, is much faster then linear search
For example of Unordered and Order data
The Unordered (by Height) Baseball Team The Ordered (by Height) Baseball Team
Bubble Sort: How Does It Work?
5
1. Start from left end of line, and
compare the two players in
position 0 and 1;
2. If the player on the left (in
position 0) is taller, swap
them. Otherwise, do nothing;
3. Then, move over one position
and compare the players in
positions 1 and 2. Again, if the
player left is taller, swap them.
Bubble Sort: End of First Pass
6
The tallest player will be swapped every time, compare two kids,
until eventually he (or she) will reach the right end of the line
After this first pass, it was (n-1) comparisons (where n – number of
players), and somewhere 0 and (n-1) swaps
The item at the end of the array is sorted and won’t be moved again
End of First Pass
Then, go back to the left end of the line, compare player 0 and 1
again, and so on to the right. At this time (second pass), will stop at
position (n-2), because the last position (n-1) is the tallest. Continue
this process until all the players are in order.
Bubble Sort: Code in C/C++
7
for( i=0; i<nElems‐1; i++ ){ //number of sorted elements or ith pass
for( j=0; j<nElems‐i‐1; j++ ){ //circle to take the tallest to the right end
if( arr[j] > arr[j+1] ){ //if the left is taller?
tmp = arr[ j ]; /*swap arr[ j ] and arr[ j+1 ] */
arr[j] = arr[ j+1 ];
arr[ j+1 ] = tmp;
} //End if
} //End j loop
} //End i loop
Please try with Bubble sort animation, here:http://cathyatseneca.github.io/DSAnim/web/bubble.html
Bubble Sort: Efficiency
8
If n – number of items in the array
So for the 1st pass there are (n-1) comparisons, 2nd
pass there are (n-2) comparisons, and so on.
Thus, total of comparisons is:
(n-1) + (n-2) + (n-3) + … + 1 = n*(n-1)/2
Because constants do NOT count in Big-O notation,
we can say that the bubble sort runs in O(n2) time.
Homework Mon., 26-Oct.-2015
submit to: @ 15:00
[email protected] 9
Write a function, which will sort data of array by ascending or
descending with Bubble sort algorithm (Option ascending or
descending will be input by user);
Explain your codes by comments;
Draw flow chart of your source codes.
10
To be continued…