Searching and Sorting Algorithms

KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS204
Data Structures 1
1433/1434H
Lab - 8
Learning Procedure
1)
Stage J (Journey inside-out the concept)
2)
Stage a1 (apply the learned)
3)
Stage v (verify the accuracy)
4)
Stage a2 (assess your work)
Term I
2013
Lab-8: Searching and Sorting Algorithms
Laboratory 3:
Statement Purpose:
This lab will give you the description and implementation some basic Searching
and Sorting Algorithms.
Activity Outcomes:
This lab teaches you the following topics:
 Learn some well-known sorting algorithms with their implementations.
 Use of Java.util.Arrays class and its under-class methods sort
and binarySearch.
 Programming practice on sort methods for sorting array elements.
Instructor Note:
As pre-lab activity, review Ch2 & Ch14, from the book Data Structures with
Java by John R. Hubbard and also the relevant instructor’s slides.
Names
I.D.
1. .……………..……………………………….
………………………………
2. ..……………………………………………..
………………………………
3. .……………………………………………...
………………………………
4. .……………………………………………..
..…………………………….
CPCS204 – The Lab Note
Lab-8
1
Term I
2013
Lab-8: Searching and Sorting Algorithms
1) tage J (Journey)
Searching Algorithms:
A. Linear Search
linear search does O(n) comparisons on average.
B. Binary Search
Binary search does O(log n) comparisons at most which is much better than
linear search.
CPCS204 – The Lab Note
Lab-8
2
Term I
2013
Lab-8: Searching and Sorting Algorithms
Sorting Algorithms:
A. Selection Sort
Methodology (Ascending):
Algorithm (implemented in JAVA):
public static void selectionSort (int[] list)
int
{
index, smallestIndex, minIndex, temp;
for (index = 0; index < list.length - 1; index++)
{
smallestIndex = index;
for (minIndex= index+ 1; minIndex< list.length; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
}
CPCS204 – The Lab Note
Lab-8
3
Term I
2013
Lab-8: Searching and Sorting Algorithms
B. Bubble Sort
Methodology:
Algorithm (implemented as JAVA code):
public static void bubbleSort(int[] list) {
int temp, counter, index;
for (counter = 0; counter < list.length; counter++) {
for (index=0; index<list.length - 1 - counter; index++)
{
if(list[index] > list[index+1]) {
temp = list[index];
list[index] = list[index+1];
list[index+1] = temp;
}
}
}
} //end bubbleSort
CPCS204 – The Lab Note
Lab-8
4
Term I
2013
Lab-8: Searching and Sorting Algorithms
2) Stage a1 (apply)
Example 1:
Built-in JAVA binarySearch()

A static method of the class Arrays for searching the array element in the given
arrays.
Uses the binary search algorithm.
Returns the index of the found element, but if element is not found then returns (-1)
Applicable to arrays of any data type object.






Array used in binarySearch() must be sorted.
The binarsearch() method with Unsorted arrays may give wrong result.
Array having duplicate elements when searched by binarySearch() method may
return any of the duplicate element.
Syntax: public static int binarySearch(Object[] array, Object key)

Task 1: Write a statement to import the library of Arrays to the below program
Task 2: Write and use a linearSearch() method to find index p of key in ar1
Task 3: Write a statement using binarySearch() to find index p of key in ar1
Task 4:
Write a statement using to sort ar1 then use again binarySearch() to
find index p of key in ar1
//Answer task 1 here
public class binary_search {
public static void main(String[] args) {
int ar1[]={2,44,5,66,78,90,23,66};
int p, key=78;
//Answer task 2 here
//Answer task 3 here
System.out.println("element found at index "+p);
//Answer task 4 here
System.out.println("element found at index "+p);
}
}
CPCS204 – The Lab Note
Lab-8
5
Term I
2013
Lab-8: Searching and Sorting Algorithms
Example 2:
Built-in JAVA sort()

The sort operation uses a slightly optimized Dual-Pivot Quick sort algorithm

that is stable and faster than traditional One-Pivot counterpart.
Runs in O(n log n)time.


Applicable to List objects consisting numbers or alphabetical content.
Syntax: public static void sort(Object[] a) or
public static void sort(Object[] a, int fromIndex, int toIndex)
Task 1:
Use the built-in JAVA sorting method for an array's elements. Besides, printing
array elements at once without loop (i.e. for or while… etc.) (Retype and try this code)
Task 2:
Clone (copy) array old to new array Arr then use sort(Object[] a, int
fromIndex, int toIndex) to sort the right-half of array Arr. Print Arr after sort.
Potential Output:
old = [41,38,48,12,28,46,33,19,10,58] // the random generated array
num = [10,12,19,28,33,38,41,46,48,58] // sorted array
Arr = [41,38,48,12,28,10,19,33,46,58] // sorted right-half of array
CPCS204 – The Lab Note
Lab-8
6
Term I
2013
Lab-8: Searching and Sorting Algorithms
3) Stage v (verify)
Programming Exercises
Ex-1:
1. Write a program that reads 10 integer numbers and sort them with 2
different sorting algorithms.
2. Create 2 public classes. One called TestSorting and the other called
Sorting.
3. Sorting class includes above 2 sorting methods (i.e. Selection, and
Bubble) and 1 more method for printing the sorted array.
4. TestSorting class includes the main method, and uses
java.util.scanner to enter 10 integers.
5. Create and object of class Sorting Sort=new Sorting().
6. Then it calls the 2 methods in class Sorting then print the original array
and the 2 sorted arrays. So, the output would be such that:
Please
Please
Please
Please
Please
Please
Please
Please
Please
Please
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
a
a
a
a
a
a
a
a
a
a
num[0]:
num[1]:
num[2]:
num[3]:
num[4]:
num[5]:
num[6]:
num[7]:
num[8]:
num[9]:
5
6
9
7
2
4
3
8
10
13
The ORIGINAL array is:
5 6 9 7 2 4 3 8 10 13
Sorted array by SELECTION sort is:
2 3 4 5 6 7 8 9 10 13
Sorted array by BUBBLE sort is:
2 3 4 5 6 7 8 9 10 13
Ex-2 (home activity):
(Sales Commissions) Use a one-dimensional array
to solve the following problem: A company pays its salespeople on a
commission basis. The salespeople receive $200 per week plus 9% of their
gross sales for that week. For example, a salesperson who grosses $5000 in
sales in a week receives $200 plus 9% of $5000, or a total of $650. Write an
application (using an array of counters) that determines how many of the
salespeople earned salaries in each of the following ranges (assume that each
salesperson's salary is truncated to an integer amount):
CPCS204 – The Lab Note
Lab-8
7
Term I
2013
Lab-8: Searching and Sorting Algorithms
$200-299
$300-399
$400-499
$500-599
$600-699
$700-799
$800-899
$900-999
$1000 and over
Summarize the results in tabular format.
4) Stage a2 (assess)
Lab Work:
In each laboratory you are assessed on your work within lab session based on
your participation, discussions and achievement of lab activities. Thus, each lab
has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is
used to evaluate your work. This checklist accounts the following criteria:






Following the lab manual step by step
Answering given questions concisely and precisely
Practicing and implementing given examples correctly
Writing code of required programming tasks
Being focused, positive, interactive and serious during lab session
Asking good questions or answering instructor questions if any
Note: performing given home activities or extra programming is highly
recommended to improve your understanding, capability and programming
skills.
CPCS204 – The Lab Note
Lab-8
8