Professional Documents
Culture Documents
Sorting
Sorting
Sorting
8 20 8 5 10 7
Turkan Ahmed
Computer Eng. Dept. , Collage of Eng., University of Mosul
2
What is Sorting?
Sorting: an operation that segregates items
into groups according to specified criterion.
A={3162134590}
A={0112334569}
• Internal Sort
– The data to be sorted is all stored in the computer’s
main memory.
• External Sort
– Some of the data to be sorted might be stored in some
external, slower, device.
Why Sort and Examples
3
Consider:
● Sorting Books in Library (Dewey system)
● Sorting Individuals by Height (Feet and Inches)
● Sorting Movies in Blockbuster (Alphabetical)
● Sorting Numbers (Sequential)
General Sorting
4
Assumptions
data in linear data structure
availability of comparator for elements
availability of swap routine (or shift )
no knowledge about the data values
Swap (in an Array)
5
● Swap Sort
●Merge Sort
● Shell Sort
● Heap Sort
Bubble Sort
7
• list[0]...list[n - 1]
– List of n elements, indexed 0 to n - 1
Bubble Sort
8
• Series of n - 1 iterations
– Successive elements list[index] and
list[index + 1] of list are compared
– If list[index] > list[index + 1]
• Elements list[index] and list[index + 1] are
swapped
• Smaller elements move toward the top
• Larger elements move toward the bottom
Bubble Sort
9
Bubble Sort
10
Bubble Sort
11
Bubble Sort
12
Bubble Sort Example
13
Start – Unsorted
Compare, no swap
Compare, noswap
Pass 2
swap (0, 1)
no swap
no swap
swap (3, 4)
21 in position
Bubble Sort Example
15
Pass 3
no swap
no swap
swap (2, 3)
12 in position, Pass 4
no swap
swap (1, 2)
8 in position, Pass 5
swap (1, 2)
Done
Bubble Sort Algorithm
16
Bubble Sort – Algorithm Complexity
17
• Idea:
– Find the smallest element in the array
– Exchange it with the element in the first position
– Find the second smallest element and exchange it with
the element in the second position
– Continue until the array is sorted
• Disadvantage:
– Running time depends only slightly on the amount of order
in the file
Selection Sort
24
Rearrange the list by selecting an element in the list and moving it to its
proper position
Finds the location of the smallest element in the unsorted portion of the list
Moves it to the top of the unsorted portion of the list
Selection Sort
25
Selection Sort
26
Selection Sort
27
5 5 5 5 5 5 5
7 7 7 7 7 7 7
24 16 16 16 16 16 16
30 30 24 24 24 24 24
62 62 62 30 30 30 30
45 45 45 45 45 45 45
16 24 30 62 62 62 55
55 55 55 55 55 55 62
Selection Sort
28
33
Insertion Sort
34
Insertion Sort
35
Insertion Sort
36
input array
5 2 4 6 1 3
at each iteration, the array is divided in two sub-arrays:
unsorted
sorted
36
Insertion Sort
37
37
38
Insertion Sort
Reduces number of key comparisons made
in selection sort
Can be applied to both arrays and linked
lists.
Sorts list by
Comparisons Exchanges