SortingAlgorithms - 1
SortingAlgorithms - 1
SortingAlgorithms - 1
• Input:
• Output:
3
Sorting Algorithms
• There are many sorting algorithms, such as:
– Selection Sort
– Insertion Sort
– Bubble Sort
23 78 45 8 32 56 Original List
8 78 45 23 32 56 After pass 1
8 23 45 78 32 56 After pass 2
After pass 3
8 23 32 78 45 56
8 23 32 45 78 56 After pass 4
After pass 5
8 23 32 45 56 78
Selection Sort (cont.)
12
13
Insertion Sort
6 10 24 36
12
14
Insertion Sort
6 10 24 3
6
12
15
Sorted Unsorted
23 78 45 8 32 56 Original List
23 78 45 8 32 56 After pass 1
23 45 78 8 32 56 After pass 2
After pass 3
8 23 45 78 32 56
8 23 32 45 78 56 After pass 4
After pass 5
8 23 32 45 56 78
INSERTION-SORT
Alg.: INSERTION-SORT(A) 1 2 3 4 5 6 7 8
a1 a2 a3 a4 a5 a6 a7 a8
for j ← 2 to n
do key ← A[ j ] key
i←j-1
while i > 0 and A[i] > key
do A[i + 1] ← A[i]
i←i–1
A[i + 1] ← key
• Insertion sort – sorts the elements
17 in place
Comparisons and Exchanges in Insertion
Sort
INSERTION-SORT(A) cost times
c1 n
for j ← 2 to n
c2 n-1
do key ← A[ j ] 0 n-1
Insert A[ j ] into the sorted sequence A[1 . . j -1]
c4 n-1
i←j-1 comparisons
c5
t
n
(t
n
do A[i + 1] ← A[i] j 2 j 1)
c7
n-1 (t
n
i ← i – 1 exchanges j 1)
c8 j 2
A[i + 1] ← key
18
Insertion Sort – Analysis
• Running time depends on not only the size of the array but also
the contents of the array.
• Best-case: O(n)
– Array is already sorted in ascending order.
– Inner loop will not be executed.
– The number of moves: 2*(n-1) O(n)
– The number of key comparisons: (n-1) O(n)
• Worst-case: O(n2)
– Array is in reverse order:
– Inner loop is executed i-1 times, for i = 2,3, …, n
– The number of moves: 2*(n-1)+(1+2+...+n-1)= 2*(n-1)+ n*(n-1)/2 O(n2)
– The number of key comparisons: (1+2+...+n-1)= n*(n-1)/2 O(n2)
• Average-case: O(n2)
– We have to look at all possible initial data organizations.
• So, Insertion Sort is O(n2)
Bubble Sort
• The list is divided into two sublists: sorted and
unsorted.
• The smallest element is bubbled from the unsorted
list and moved to the sorted sublist.
• After that, the wall moves one element ahead,
increasing the number of sorted elements and
decreasing the number of unsorted ones.
• Each time an element moves from the unsorted
part to the sorted part one sort pass is completed.
• Given a list of n elements, bubble sort requires up
to n-1 passes to sort the data.
Bubble Sort
23 78 45 8 32 56 Original List
Bubble Sort (Pass 1)
23 78 45 8 32 56
23 45 78 8 32 56
23 45 8 78 32 56
23 45 8 32 78 56
23 45 8 32 56 78
23 45 8 32 56 78
Bubble Sort (Pass 2)
23 45 8 32 56 78
23 8 45 32 56 78
23 8 32 45 56 78
23 8 32 45 56 78
23 8 32 45 56 78
Bubble Sort Algorithm
void bubbleSort(Item a[], int n)
{
boolean sorted = false;
int last = n-1;