0% found this document useful (0 votes)
47 views7 pages

Chapter 1 - Introducing Data Structures and Algorithms - 5 PDF

Uploaded by

klsfjldsfl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views7 pages

Chapter 1 - Introducing Data Structures and Algorithms - 5 PDF

Uploaded by

klsfjldsfl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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
Insertion Sort: How Does It Work?
3

1. Marked player and take


it out;
2. Find position for the
marked player (by move
the taller to right);
3. Insert the marked player
to the found position;
4. Go to 1st point, until the
end of right (last player).
Insertion Sort: Code in C/C++
4
for( i=1; i<nElems; i++){ //marked ith element or divided by i
tmp = arr[ i ]; //remove marked item

j = i; //Start shifts at ith

while( j>0 && arr[ j-1 ]>=tmp ){//Until the one is smaller
arr[ j ] = arr[ j-1 ]; //Otherwise, shift item to right

--j; //Go left one position

}
arr[ j ] = tmp; //insert marked item

Insertion Animations: http://cathyatseneca.github.io/DSAnim/web/insertion.html


http://www.ee.ryerson.ca/~courses/coe428/sorting/insertionsort.html
Insertion Sort: Efficiency
5

 If n – number of items in the array


 How many comparisons does it require?
 For the 1st pass there is 1 comparison, 2nd pass there
are 2 comparisons (maximum), and so on up to
maximum (n-1)
 Thus, total of comparisons is:
1 + 2 + 3 +…+ (n-1) = n*(n-1)/2
 So, insertion sort runs in Big-O(n2) time for random
data.
 In case, the data is almost sorted, what is the run
time of Bubble? And Insertion?
Homework5 Thu., 29-Oct.-2015
submit to: @ 15:00
[email protected]
6

 Write a function, which will sort data of array by ascending or


descending with Insertion sort algorithm (Option ascending or
descending will be input by user);
 Explain your codes by comments;
 Draw flow chart of your source codes.

Please send your homework only to [email protected]


With title: Your Full Name and Homework# (Example: Chan Bopha Homework 5
Attachment file PDF with Name: YourFullName and Homework# (Chan_Bopha_Homework5.pdf)
7

End of Chapter 1

You might also like