Exercise For Sorting and Searching in Data Structure N Skema 2014
Exercise For Sorting and Searching in Data Structure N Skema 2014
1. The selection sort is an attempt to localize the exchanges of array elements by finding a
misplaced element first and putting it in its final place. The element with the lowest value
is selected and exchanged with the element in the first position. Then the smallest value
among the remaining elements is found and put in the second position.
Based on the following problems, sort each of items by using selection sort.
a. 10 5 100 8 2
b. Dog Ewe Ram Cat Cow Hen
2. The structure of the bubble sort is similar to that of the selection sort. Besides searching
for the smallest element in an array and doing simple swap at each pass, adjacent
elements are compared and rearranged as necessary until whole list is completely
ordered.
Based on the following problems, sort each of items by using bubble sort.
a. 6 1 2 5 4 3
b. S Y A M P O
3. Quick sort uses divide and conquer technique, where the array or list is partitioned into
two parts and an element is chosen as a pivot key. One part contains elements that are
less than or equal to pivot and the other part contains elements that are greater than the
pivot. Each of the two parts is recursively sorted until the whole array gets sorted.
Based on the following problems, sort each of items by using quick sort.
a. 67 33 21 84 49 50 75
b. P A V I L E M
4. In linear search, items in a list are searched one by one (starting from the first) and
compared to given key value. The search ends when the key value matches with the
given item.
The following is unsorted list. By using linear searching, find how many steps needed to
find the desired value. Illustrate the process.
a. Find 5 in : {7 19 10 5 100 8 2}
b. Find M in : {C O M P U T E R}
The binary search algorithm searches the list by first comparing the key sought with the
middle element in the list. Binary search requires the sorted list.
The following is sorted list. By using binary searching, find how many steps needed to
find the desired value. Illustrate the process.
a. Find 15 in : {7 12 15 38 88}
b. Find 9 in : {4 7 9 10 17 23 34 45 50 65 89}
c. Find S in : {A D G H J L R T}
Answer
1. Selection sort
a. 10 5 100 8 2
2 5 100 8 10
2 5 100 8 10
2 5 8 100 10
2 5 8 10 100
2. Bubble sort
a. 6 1 2 5 4 3
1 6 2 5 4 3
1 2 6 5 4 3
1 2 5 6 4 3
1 2 5 4 6 3
1 2 5 4 3 6
1 2 5 4 3 6
1 2 4 5 3 6
1 2 4 3 5 6
1 2 4 3 5 6
1 2 3 4 5 6
b. S Y A M P O
3. quick sort
1) 67 33 21 84 49 50 75
pivot
2) 67 33 21 50 49 84 75
3) 49 33 21 50 67 84 75
pivot
4) 21 33 49 50 67 84 75
pivot
5) 21 33 49 50 67 84 75
pivot
6) 21 33 49 50 67 84 75
pivot
7) 21 33 49 50 67 84 84
pivot
8) 21 33 49 50 67 75 84
9) 21 33 49 50 67 75 84
Pivot
P A V I L E M
4. linear searching
a. 7 19 10 5 100 8 2 4 steps
b. C O M P U T E R 3 steps
5. binary searching