Professional Documents
Culture Documents
CO1401 Week 8 Lecture
CO1401 Week 8 Lecture
Programming
Week 8
Sorting & Strings
Topics
• Insertion Sort
• Strings
2 Programming
Algorithms
3 Programming
Algorithms
4 Programming
Sorting
6 Programming
insertion sort
7 Programming
insertion sort
8 Programming
insertion sort
9 Programming
insertion sort
10 Programming
insertion sort
11 Programming
Insertion sort
12 Programming
Insertion sort
13 Programming
Insertion Sort
• 6 3 1 9 4 12 17 2
• 3 6 1 9 4 12 17 2
• 1 3 6 9 4 12 17 2
• 1 3 6 9 4 12 17 2
• 1 3 4 6 9 12 17 2
• 1 3 4 6 9 12 17 2
• 1 3 4 6 9 12 17 2
• 1 2 3 4 6 9 12 17
14 Programming
Insertion Sort
15 Programming
Insertion Sort - the algorithm
• We also use an inner loop. The inner loop starts from the
highest (right hand side) of the sorted array. It "slides" the
numbers across.
• The loop progressively goes through the sorted array until
it find the correct place to put the value to be inserted.
16 Programming
Insertion Sort - code
void insertionSort(int numbers[], int arraySize)
{
int i, j, insert;
18 Programming
Insertion Sort - efficiency
19 Programming
Insertion Sort - implementation efficiency
20 Programming
Insertion Sort - implementation efficiency
21 Programming
Topic 2
• Strings
22 Programming
Strings
23 Programming
Strings
24 Programming
Strings
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << str.length();
}
25 Programming
String operators: length
26 Programming
String operators: compare
• compare
• Compares two strings. Note that the comparison uses
the ASCII coding, so this provides only a limited ability
to alphabetical sorting
• 0 if same
• -1 if alphabetically smaller
• 1 if alphabetically larger
27 Programming
String operators
• concatenation (joining)
str = str1 + str2;
28 Programming
String operators - find
29 Programming
String operators - size_t
31 Programming
String operators - replace
33 Programming