Вы находитесь на странице: 1из 147

Sorting Algorithms

General definition
The basic objective of sorting is always the same: taking a
list of unorganized items, and arranging them to a certain
order.

• Putting a number of elements into a list in which the


elements are in increasing order
– Input:
• A sequence of n numbers <a1, a2, …, an>
– Output:
• A permutation (reordering) <a’1, a’2, …, a’n> of the input
sequence such that a’1 ≤ a’2 ≤ … ≤ a’n
SORTING
Pengurutan menaik (Ascending) berarti menyusun
elemen larik sedemikian rupa sehingga
L[1] ≤ L[2] ≤ L[3] ≤ …… ≤ L[N]

Pengurutan menurun (Desending) berarti


menyusun elemen larik sedemikian rupa sehingga
L[1] ≥ L[2] ≥ L[3] ≥ …… ≥ L[N]
Sorting Algorithms
 Simple sorts
 Insertion sort
 Selection sort
 Efficient sorts
 Merge sort
 Heap sort
 Quick sort
 Bubble sort and variants
 Bubble sort
 Shell sort
 Comb sort
 Distribution sort
 Counting sort
 Bucket sort
 Radix sort
Selection Sort
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

6
Selection sort
Given an array of length n,
Search elements 0 through n-1 and select the smallest
 Swap it with the element in location 0
Search elements 1 through n-1 and select the smallest
 Swap it with the element in location 1
Search elements 2 through n-1 and select the smallest
 Swap it with the element in location 2
Search elements 3 through n-1 and select the smallest
 Swap it with the element in location 3
Continue in this fashion until there’s nothing left to
search
7
Selection Sort Algorithm

8 4 6 9 2 3 1
Alg.: SELECTION-SORT(A)
n ← length[A]
for j ← 1 to n - 1
do smallest ← j
for i ← j + 1 to n
do if A[i] < A[smallest]
then smallest ← i
exchange A[j] ↔ A[smallest]

8
Selection Sort
Selection_sort_algorithm
set current_smallest_position to 1
DOWHILE current_smallest_position ≤ (number_of_elements - 1)
set I to current_smallest_position
smallest_element = Array(I)
set J = I + 1
DOWHILE J ≤ number_of_elements
IF Array(J) < smallest_element THEN
I = J
smallest_element = Array(J)
ENDIF
J = J + 1
ENDDO
Array(I) = Array(current_smallest_position)
Array(current_smallest_position) = smallest_element
Add 1 to current_smallest_position
ENDDO
END
#include<stdio.h>  for(i=0; i<SIZE; i++)
#include<conio.h> {
#define SIZE 10 min=i;
for(j=i+1; j<SIZE; j++)
if(arr[j]<arr[min])
int main()
min=j;
{
temp=arr[i];
int i,j,min,temp;
arr[i]=arr[min];
int arr[SIZE];
arr[min]=temp;
for(i=0; i<SIZE; i++) }
{ printf("After selection sort the elements:\n");
printf("Enter element : "); for(i=0; i<SIZE; i++)
scanf("%d",&arr[i]); printf("%d\t",arr[i]);
} getch();
return 0;
}
Output
Enter element : 21
Enter element : 3
Enter element : 45
Enter element : 87
Enter element : 72
Enter element : 14
Enter element : 54
Enter element : 75
Enter element : 44
Enter element : 5

After selection sort the elements :


3 5 14 21 44 45 54 72 75 87
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
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

13
To insert 12, we need to
make room for it by moving
first 36 and then 24.
6 10 2 4 3 6

12

14
6 10 2 4 36

12

15
6 10 24 3
6

12

16
Insertion Sort
input array 

5      2      4      6      1      
3
at each iteration, the array is divided in two sub-arrays:

left sub-array right sub-array

sorted unsorted

17
Insertion Sort

18
Insertion-sort
Alg.: INSERTION-SORT(A) 1 2 3 4 5 6 7 8

for j ← 2 to n a 1 a2 a3 a4 a5 a6 a7 a8

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 in place

19
Insertion Sort
Insertion_sort_algorithm
set I to 1
DOWHILE I ≤ (number_of_elements - 1)
IF Array(I) > Array(I + 1) THEN
temp = Array(I)
J = I
DOWHILE (J ≥ 1 AND Array(J) > temp)
Array(J + 1) = Array(J)
J = J - 1
ENDDO
Array(J + 1) = temp
ENDIF
I = I + 1
ENDDO
END
#include<stdio.h>  for (i = 1; i < num; i++) {
temp = arr[i];
int main() { j = i - 1;
int i, j, num, temp, arr[20]; while ((temp < arr[j]) && (j >= 0)) {
printf("Enter total elements: "); arr[j + 1] = arr[j];
scanf("%d", &num); j = j - 1;
}
printf("Enter %d elements: ",
num); arr[j + 1] = temp;
}
for (i = 0; i < num; i++) {
printf("After Sorting: ");
scanf("%d", &arr[i]);
for (i = 0; i < num; i++) {
}
printf("%d", arr[i]);
}
return 0;
}

Output
Enter total elements: 5
Enter 5 elements: 9 4 1 0 2
After sorting: 0 1 2 4 9
Bubble sort
 Compare each element (except the last one) with its
neighbor to the right
 If they are out of order, swap them
 This puts the largest element at the very end
 The last element is now in the correct and final place
 Compare each element (except the last two) with its
neighbor to the right
 If they are out of order, swap them
 This puts the second largest element next to last
 The last two elements are now in their correct and final places
 Compare each element (except the last three) with its
neighbor to the right
 Continue as above until you have no unsorted elements on the left

22
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8

2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8

2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 (done)

2 7 5 8 4 2 5 4 7 8

2 7 5 4 8

23
Contoh
N 8 did_swap true

to_do 7

index

98 23 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap false

to_do 7

index 1

98 23 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap false

to_do 7

index 1

Swap

98 23 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 1

Swap

23 98 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 2

23 98 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 2

Swap

23 98 45 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 2

Swap

23 45 98 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 3

23 45 98 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 3

Swap

23 45 98 14 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 3

Swap

23 45 14 98 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 4

23 45 14 98 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 4

Swap

23 45 14 98 6 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 4

Swap

23 45 14 6 98 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 5

23 45 14 6 98 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 5

Swap

23 45 14 6 98 67 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 5

Swap

23 45 14 6 67 98 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 6

23 45 14 6 67 98 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 6

Swap

23 45 14 6 67 98 33 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 6

Swap

23 45 14 6 67 33 98 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 7

23 45 14 6 67 33 98 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 7

Swap

23 45 14 6 67 33 98 42

1       2        3      4        5      6        7       8
An Animated Example
N 8 did_swap true

to_do 7

index 7

Swap

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
After First Pass of Outer Loop
N 8 did_swap true

to_do 7

index 8 Finished first “Bubble Up”

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap false

to_do 6

index 1

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap false

to_do 6

index 1

No Swap

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap false

to_do 6

index 2

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap false

to_do 6

index 2

Swap

23 45 14 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 2

Swap

23 14 45 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 3

23 14 45 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 3

Swap

23 14 45 6 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 3

Swap

23 14 6 45 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 4

23 14 6 45 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 4

No Swap

23 14 6 45 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 5

23 14 6 45 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 5

Swap

23 14 6 45 67 33 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 5

Swap

23 14 6 45 33 67 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 6

23 14 6 45 33 67 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 6

Swap

23 14 6 45 33 67 42 98

1       2        3      4        5      6        7       8
The Second “Bubble Up”
N 8 did_swap true

to_do 6

index 6

Swap

23 14 6 45 33 42 67 98

1       2        3      4        5      6        7       8
After Second Pass of Outer
Loop
N 8 did_swap true

to_do 6

index 7 Finished second “Bubble Up”

23 14 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap false

to_do 5

index 1

23 14 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap false

to_do 5

index 1

Swap

23 14 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 1

Swap

14 23 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 2

14 23 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 2

Swap

14 23 6 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 2

Swap

14 6 23 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 3

14 6 23 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 3

No Swap

14 6 23 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 4

14 6 23 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 4

Swap

14 6 23 45 33 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 4

Swap

14 6 23 33 45 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 5

14 6 23 33 45 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 5

Swap

14 6 23 33 45 42 67 98

1       2        3      4        5      6        7       8
The Third “Bubble Up”
N 8 did_swap true

to_do 5

index 5

Swap

14 6 23 33 42 45 67 98

1       2        3      4        5      6        7       8
After Third Pass of Outer Loop
N 8 did_swap true

to_do 5

index 6 Finished third “Bubble Up”

14 6 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap false

to_do 4

index 1

14 6 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap false

to_do 4

index 1

Swap

14 6 23 33 42 45 67 98

1     2    3     4      5    6     7     8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 1

Swap

6 14 23 33 42 45 67 98

1     2    3     4      5    6     7     8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 2

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 2

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 3

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 3

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 4

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fourth “Bubble Up”
N 8 did_swap true

to_do 4

index 4

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
After Fourth Pass of Outer Loop
N 8 did_swap true

to_do 4

index 5 Finished fourth “Bubble Up”

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 1

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 1

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 2

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 2

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 3

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
The Fifth “Bubble Up”
N 8 did_swap false

to_do 3

index 3

No Swap

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
After Fifth Pass of Outer Loop
N 8 did_swap false

to_do 3

index 4 Finished fifth “Bubble Up”

6 14 23 33 42 45 67 98

1       2        3      4        5      6        7       8
Finished “Early”
N 8 did_swap false

to_do 3
We didn’t do any swapping,
index 4 so all of the other elements
must be correctly placed.

We can “skip” the last two
passes of the outer loop.

6 14 23 33 42 45 67 98
Bubble Sort: Algorithm
for pass = 1 .. n-1
exchange = false
for position = 1 .. n-pass
if element at position < element at position +1
exchange elements
exchange = true
end if
next position
if exchange = false BREAK
next pass
Algorithm Bubble sort
Input: unsorted sequence a1, a2, …, an
Output: sorted sequence a1, a2, …, an
for (outer = a.length - 1; outer > 0; outer--) {
// counting down
for (inner = 0; inner < outer; inner++) {
// bubbling up
if (a[inner] > a[inner + 1]) { // if out of order...
int temp = a[inner]; // ...then swap
a[inner] = a[inner + 1];
a[inner + 1] = temp;
}
}
}
98
Bubble Sort Algorithm
Alg.: BUBBLESORT(A)
for i  1 to length[A]
do for j  length[A] downto i + 1
do ifi A[j] < A[j -1]
then exchange A[j]  A[j-1]

8 4 6 9 2 3 1
i = 1 j

99
Bubble Sort
Bubble_sort_algorithm
set I to number_of_elements
set elements_switched to true
DOWHILE (elements_switched AND I ≥ 2)
set J to 1
set elements_switched to false
DOWHILE J ≤ I - 1
IF Array(J) > Array(J + 1) THEN
temp = Array(J)
Array(J) = Array(J + 1)
Array(J + 1) = temp
elements_switched = true
ENDIF
J = J + 1
ENDDO
I = I - 1
ENDDO
END
Bubble sorting steps

1. Start from left hand side


2. Compare first two numbers
3. If first_number > second_number than swap both
number position. And if first_number < second_number
than these compare next two numbers i.e. second_number
and third_number.
4. Step-3 process repeat until there are no more numbers left
to compared.
5. Bubble sorting completed.

An example on bubble sort.


To understand logic of Bubble Sorting, lets take random

numbers: 6 3 7 1 4 5 2
First iteration Third iteration Six iteration
3 7 1 4 5 2 3 1 4 5 2 6 7 1 2 3 4 5 6 7
3 6 7 1 4 5 2 1 3 4 5 2 6 7
3 6 7 1 4 5 2 1 2 3 4 5 6 7
1 3 4 5 2 6 7
3 6 1 7 4 5 2
3 6 1 4 7 5 2 1 3 4 5 2 6 7
3 6 1 4 5 7 2 1 3 4 2 5 6 7 Seven iteration
3 6 1 4 5 2 7 1 2 3 4 5 6 7

Second iteration Four iteration


3 6 1 4 5 2 7 1 3 4 2 5 6 7
3 6 1 4 5 2 1 3 4 2 5 6 7
3 1 6 4 5 2 7
1 3 4 2 5 6 7
3 1 4 6 5 2 7
3 1 4 5 6 2 7
1 3 2 4 5 6 7
3 1 4 5 2 6 7
Five iteration
1 3 2 4 5 6 7
1 3 2 4 5 6 7
1 2 3 4 5 6 7
 for(i=0; i<SIZE ; i++)
#include<stdio.h> { Output:-
#include<conio.h> for(j=0; j<(SIZE-1)-i; j++)
Enter number : 6
#define SIZE 7 {
if( arr[j] < arr[j+1] ) Enter number : 3
int main()
{ Enter number : 7
{
temp=arr[j]; Enter number : 1
int i,j,temp; arr[j]=arr[j+1]; Enter number : 4
int arr[ SIZE ]; arr[j+1]=temp;
}
Enter number : 5
for(i=0; i<SIZE; i++)
} Enter number : 2
{
printf("%d\t",arr[j]); 1 2 3 4 5 6 7
printf("Enter Number : }
"); getch();
scanf("%d",&arr[i]); return 0;
} }
Searching
Searching involved looking for an element in a list.
If the list is unsorted, you have to look at everything.
But what about if the list is sorted?
Searching
Sequential search
Search begins at the beginning of the list and
continues until the item is found or the entire list
has been searched
Binary search (list must be sorted)
Search begins at the middle and finds the item or
eliminates half of the unexamined items; process is
repeated on the half where the item might be
Say that again…
The Linear Search

This is a very simple algorithm.


It uses a loop to sequentially step through an array,
starting with the first element.
It compares each element with the value being
searched for and stops when that value is found or the
end of the array is reached.

108
LINEAR SEARCH
#include<stdio.h>   printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
int main(){
if(a[i]==m){
int a[10],i,n,m,c=0; c=1;
printf("Enter the size of an array: "); break;
scanf("%d",&n); }
printf("Enter the elements of the array: "); }
if(c==0)
for(i=0;i<=n-1;i++){
printf("The number is not in the list");
scanf("%d",&a[i]); else
} printf("The number is found");
   return 0;
}
Sample output:
Enter the size of an array: 5
Enter the elements of the array: 4 6 8 0 3
Enter the number to be search: 0
The number is found
Binary Search
The binary search is much more efficient than the
linear search.
It requires the list to be in order.
The algorithm starts searching with the middle
element.
If the item is less than the middle element, it
starts over searching the first half of the list.
If the item is greater than the middle element,
the search starts over starting with the middle
element in the second half of the list.
It then continues halving the list until the item is
found.
110
Binary Search
The binary search first compares the key 
with the element in the middle of the 
array. Consider the following three cases:
If the key is less than the middle 
element, you only need to search the key 
in the first half of the array.
 If the key is equal to the middle 
element, the search ends with a match.
If the key is greater than the middle 
element, you only need to search the key 
in the second half of the array.
Binary Search, cont.
key = 11

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list 2 4 7 10 11 45 50 59 60 66 69 70 79

key < 50 mid

[0] [1] [2] [3] [4] [5]


2 4 7 10 11 45

key > 7 mid

[3] [4] [5]


10 11 45

key = 11 mid
Example 5.11
Testing Binary Search
Objective: Implement and test the binary 
search method. The program first 
creates an array of 10 elements of 
int type. It displays this array and 
then prompts the user to enter a key 
for testing binary search. 

BinarySearch Run
Example 5.12
Using Arrays in Sorting
Objective: Use the selectionSort method to
write a program that will sort a list of double
floating-point numbers.

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted


Sort it to produce 1, 2, 4, 5, 6, 8, 9

2, 9, 5, 4, 8, 1, 6

SelectionSort Run
Binary Search

Figure 9.14 Trace of the binary search


Binary search
#include <stdio.h> while (first <= last)
{
int main()
if (array[middle] < search)
{ first = middle + 1;
int c, first, last, middle, n, search, else
array[100]; if (array[middle] == search)
printf("Enter number of elements\n"); {
scanf("%d",&n); printf("%d found at location
printf("Enter %d integers\n", n); %d.\n",
search, middle+1);
for (c = 0; c < n; c++)
break;
scanf("%d",&array[c]); }
else last = middle - 1;
printf("Enter value to find\n"); middle = (first + last)/2;
scanf("%d", &search); }
if (first > last)
first = 0; last = n - 1;
printf("Not found! %d is not
middle = (first+last)/2;
present in the list.\n", search);
return 0;
}
Data abstraction
Data Type
A data type is a collection of objects and a set of
operations that act on those objects.
For example, the data type int consists of the objects {0, +1,
-1, +2, -2, …, INT_MAX, INT_MIN} and the operations +, -, *,
/, and %.
The data types of C
The basic data types: char, int, float and double
The group data types: array and struct
The pointer data type
The user-defined types
Data abstraction
Abstract Data Type
An abstract data type(ADT) is a data type
that is organized in such a way that
the specification of the objects and
the operations on the objects is separated from
the representation of the objects and
the implementation of the operations.
We know what is does, but not necessarily how it will do
it.
Queues
Queue
An abstract data type in which items are entered at one
end and removed from the other end
FIFO, for First In First Out

No standard queue terminology


 Enqueue, Enque, Enq, Enter, and Insert Name
are used for the insertion operation three
 Dequeue, Deque, Deq, Delete, and Remove everyday
are used for the deletion operation. structures
that are
queues
Queue
a particular kind of abstract data enqueue
type or collection in which the
entities in the collection are
kept in order and the principal
(or only) operations on the
collection are the addition of
entities to the rear terminal
position, known as enqueue,
and removal of entities from the
front terminal position, known dequeue
as dequeue. This makes the
queue a First-In-First-Out
(FIFO) data structure.
What Is Queue
Queue is an abstract data type
Adding an entry at the rear
Deleting an entry at the front

Adding
Adding Deleting
Deleting
C B A

rear
rear front
front

123
Queue
Queue
Operating on both ends
Operations: EnQueue(in), DeQueue(out)

enqueu
enqueu
ee dequeue
dequeue
C B A

rear
rear front
front

124
Queue
Queue is FIFO ( First-In First-Out)

A queue is open at two ends. You can only add entry


(enqueue) at the rear , and delete entry (dequeue)
at the front.

Note that you cannot add/extract entry in the


middle of the queue.

125
Queue
Queue: First In First Out (FIFO)

Input D C B A Output

Toll Station
Car comes, pays, leaves
Check-out in Big Y market
Customer comes, checks out and leaves
More examples: Printer, Office Hours, …

126
More Examples of Queue
In our daily life
Airport Security Check
Cinema Ticket Office
Bank, ATM
Anything else ?

127
Queue

Add_item_to_tail_of_queue Remove_item_to_head_of_queue
IF (queue_tail = queue_head AND IF queue_counter = 0 THEN
queue_counter > 0) THEN Print error message (‘queue is
Print error message (‘queue empty’)
overflow’) ELSE
ELSE required value = Queue (queue_head)
Queue (queue_tail) = new item queue_head = queue_head + 1
queue_tail = queue_tail + 1 IF queue_head > max_size THEN
IF queue_tail > max_size THEN queue_head = 1
queue_tail = 1 ENDIF
ENDIF queue_counter = queue_counter - 1
queue_counter = queue_counter + 1 ENDIF
ENDIF END
END
Array Implementation of
Queue
n-1 3 2 1 0
DCBA

Max_Size rear front

After A leaves, 
n-1 3 2 1 0
DCB

Max_Size rear front

129
Stacks
Stack
An abstract data type in which accesses are made at only
one end
LIFO, which stands for Last In First Out

The insert is called Push and the delete is called Pop


Stacks
is an abstract data type that push pop
serves as a collection of
elements, with two principal
operations: push, which adds an
element to the collection, and
pop, which removes the last
element that was added.
Stacks

Add_item_to_top_of_stack (Push) Remove_item_to_top_of_stack (Pop)


IF top_of_stack NOT max_size THEN IF top_of_stack NOT zero THEN
top_of_stack = top_of_stack + 1 value required = Stack
Stack (top_of_stack) = new_item (top_of_stack)
ELSE top_of_stack = top_of_stack - 1
Print error message (‘stack ELSE
overflow’) Print error message
ENDIF (‘stack underflow’)
END ENDIF
END
Preliminaries
Options for implementing an ADT List
Array has a fixed size
 Data must be shifted during insertions and deletions
Linked list is able to grow in size as needed
 Does not require the shifting of items during insertions and
deletions
Comparing Array-Based and
Pointer-Based Implementations
Size
Increasing the size of a resizable array can waste storage
and time
Storage requirements
Array-based implementations require less memory than
a pointer-based ones
Comparing Array-Based and
Pointer-Based Implementations
Access time
Array-based: constant access time
Pointer-based: the time to access the ith node depends
on i
Insertion and deletions
Array-based: require shifting of data
Pointer-based: require a list traversal
Linked lists
a data structure consisting of a group of nodes which together
represent a sequence. Under the simplest form, each node is
composed of data and a reference (in other words, a link) to the
next node in the sequence; more complex variants add additional
links. This structure allows for efficient insertion or removal of
elements from any position in the sequence.

9 3 7 X
The composition of a Linked List
Each node in a linked list contains one or more
members that represent data.
In addition to the data, each node contains a
pointer, which can point to another node.

137
The composition of a Linked List
A linked list is called "linked" because each node in
the series has a pointer that points to the next node
in the list.

138
Linked Implementation
Linked implementation
An implementation based on the concept of a node
Node
A holder for two pieces of information
the item that the user wants in the list (item)
a pointer to the next node in the list (next)
Linked Implementation

Figure 9.4 Anatomy


Figure 9.4 Anatomy of a linked
of a linked list list
Linked Implementation

Figure 9.5 An unsorted linked list


Linked Implementation

Figure 9.6 A sorted linked list


Linked Implementation
How do we implement the operations?

Add item given current, insert a new node


with item in the info part between 
current and next(current)
Remove item given current, remove
next(current)
Get next item set current to next(current)
more items current does not contain null
Linked Implementation

Figure 9.7 Store a node with info of 67 after current


Linked Implementation

Figure 9.8 Remove node next(current)


Linked lists
Traverse_and_print Search_list_for_value
current = first current = first
DOWHILE current NOT = Null continue = true
Print items (current) DOWHILE (continue AND current NOT
current = Links (current) = Null)
ENDDO IF items (current) NOT = value
END THEN
last = current
Remove_value_from_list current = Links (current)
IF NOT continue THEN ELSE
(i.e. the value was found on the
continue = false
list)
ENDIF
IF current = first THEN
ENDDO
first = Links (current)
END
ELSE
Links (last) = Links (current)
ENDIF
ENDIF
END
Questions?

Вам также может понравиться