Download Document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Week 12
Engineering Problem 2
Outline
•
•
•
•
•
Review on Array
Sorting Problem
Insertion Sort in pseudo-code
Example
Insertion Sort in C-language
Declare an array in C
type name[elements];
• int x[20]
• float y[10]
Sorting Problem
• Given an input array
• Input: A = <a1,a2,a3,…,an> with n integers
• Output: is A = <a’1,a’2,a’3,…,a’n> where a’1≤ a’2 ≤ a’3 ≤… ≤ a’n
• There are several sorting algorithms. Here we use
Insertion Sort.
Pseudo Code for Insertion Sort)
Example of (Insertion Sort)
1,4,2,6,7
Let an input array contain the following values
Example of (Insertion Sort)
1,4,2,6,7
Red number (index 1) is compared to its preceding number
(index 0)
Example of (Insertion Sort)
1,4,2,6,7
1,4,2,6,7
Since 4 is bigger than 1, no movement here
Example of (Insertion Sort)
1,4,2,6,7
1,4,2,6,7
In the next step, 2 (index 2) is the next red number
Example of (Insertion Sort)
1,4,2,6,7
1,4,2,6,7
1,2,4,6,7
Since 2 is smaller than 4, in this case, 2 and 4 are
swapped.
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
1,2,4,6,7
Next, 2 is compared to 1. Since they are in the correct
order, no change here.
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
Then, 6 is the next red number.
1,2,4,6,7
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
1,2,4,6,7
1,2,4,6,7
Since 6 is bigger than 4, there is no movement here.
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
1,2,4,6,7
7 is the next red number.
1,2,4,6,7
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
1,2,4,6,7
1,2,4,6,7
Since 7 is bigger than 6, no movement here
Example of (Insertion Sort)
1,4,2,6,7
1,2,4,6,7
1,4,2,6,7
1,2,4,6,7
1,2,4,6,7
• . Since 7 is the highest, and this is the end of the code.
อัลกอริ ทึมการจัดเรี ยงข้อมูลแบบแทรกใน C
Example of a Run
Sorting String Data
In sorting, the key is to be able to
compare between two numbers.
Now if the data is to be sorted. One
can apply strcmp, which is
int strcmp(char *string1, char *string2);
Using strcmp command
• If string1<string2, the answer is less than 0
• If string2<string1, the answer is bigger than
0
• If string1=string2, the answer is 0
Related documents