SortingAlgorithms - 1

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 27

Sorting Algorithms

The Sorting Problem

• Input:

– A sequence of n numbers a1, a2, . . . , an

• Output:

– A permutation (reordering) a1’, a2’, . . . , an’ of the input

sequence such that a1’ ≤ a2’ ≤ · · · ≤ an’


2
Structure of data

3
Sorting Algorithms
• There are many sorting algorithms, such as:
– Selection Sort
– Insertion Sort
– Bubble Sort

• The first three are the foundations for faster


and more efficient algorithms.
Selection Sort
• The list is divided into two sublists, sorted and unsorted,
which are divided by an imaginary wall.
• We find the smallest element from the unsorted sublist
and swap it with the element at the beginning of the
unsorted data.
• After each selection and swapping, the imaginary wall
between the two sublists move one element ahead,
increasing the number of sorted elements and decreasing
the number of unsorted ones.
• Each time we move one element from the unsorted sublist
to the sorted sublist, we say that we have completed a sort
pass.
• A list of n elements requires n-1 passes to completely
rearrange the data.
Sorted Unsorted

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.)

void selectionSort( int a[], int n) {


for (int i = 0; i < n-1; i++) {
int min = i; // index of smallest element
for (int j = i+1; j < n; j++)
if (a[j] < a[min]) min = j;
swap(a[i], a[min]);
}
}

void swap( int &lhs, int &rhs )


{
int tmp = lhs;
lhs = rhs;
rhs = tmp;
}
Selection Sort -- Analysis
• In general, we compare keys and move items (or exchange items)
in a sorting algorithm (which uses key comparisons).
 So, to analyze a sorting algorithm we should count the
number of key comparisons and the number of moves.
• Ignoring other operations does not affect our final result.

• In selectionSort function, the outer for loop executes n-1 times.


• We invoke swap function once at each iteration.
 Total Swaps: n-1
 Total Moves: 3*(n-1) (Each swap has three
moves)
Selection Sort – Analysis (cont.)
• The inner for loop executes the size of the unsorted part minus 1
(from 1 to n-1), and in each iteration we make one key
comparison.
 # of key comparisons = 1+2+...+n-1 = n*(n-1)/2
 So, Selection sort is O(n2)
• The best case, the worst case, and the average case of the
selection sort algorithm are same.  all of them are O(n2)
Selection Sort – Analysis (cont.)
– This means that the behavior of the selection sort algorithm
does not depend on the initial organization of data.
– Since O(n2) grows so rapidly, the selection sort algorithm is
appropriate only for small n.
– Although the selection sort algorithm requires O(n2) key
comparisons, it only requires O(n) moves.
– A selection sort could be a good choice if data moves are
costly but key comparisons are not costly (short keys, long
records).
Insertion Sort
• Insertion sort is a simple sorting algorithm that is
appropriate for small inputs.
– Most common sorting technique used by
card players.
• The list is divided into two parts: sorted and
unsorted.
• In each pass, the first element of the unsorted part is
picked up, transferred to the sorted sublist, and
inserted at the appropriate place.
• A list of n elements will take at most n-1 passes to
sort the data.
Insertion Sort
• Idea: like sorting a hand of playing cards
– Start with an empty left hand and the cards facing
down on the table.
– Remove one card at a time from the table, and insert
it into the correct position in the left hand
• compare it with each of the cards already in the hand,
from right to left
– The cards held in the left hand are sorted
• these cards were originally the top cards of the pile on the
table
12
Insertion Sort

To insert 12, we need to


make room for it by moving
first 36 and then 24.
6 10 24 36

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

Insert A[ j ] into the sorted sequence A[1 . . j -1]

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

while i > 0 and A[i] > key c6


j 2 j

 (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;

for (int i = 0; (i < n-1) && !sorted; i++){


sorted = true;
for (int j=0; j < n-i-1; j++)
if (a[j] > a[j+1]{
swap(a[j],a[j+1]);
sorted = false; // signals exchange
}
}
}
Bubble Sort – Analysis
• Best-case:  O(n)
– Array is already sorted in ascending order.
– The number of moves: 0  O(1)
– The number of key comparisons: (n-1)  O(n)
• Worst-case:  O(n2)
– Array is in reverse order:
– Outer loop is executed n-1 times,
– The number of moves: 3*(1+2+...+n-1) = 3 * 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, Bubble Sort is O(n2)
TEST – 3 (5 marks)
Question 1(3 marks) Question 2 (2 marks)
Write an algorithm / Write code for
pseudocode to sort an array of Alternate pass
‘n’ binary numbers in O(n) time. bubble sort
Eg:
In the first pass loop
Input: runs from right to left
0,1,0,0,1,1,0,0,1,0 and in second pass
Output: from left to right and
0,0,0,0,0,0,1,1,1,1 so on…

You might also like