0% found this document useful (0 votes)
171 views11 pages

Searching and Sorting Programs

This document contains instructions for a lab on searching and sorting algorithms. It includes pseudocode and Java code examples for selection sort, bubble sort, linear search, and binary search algorithms. It also provides examples for using the built-in Java utility methods Arrays.sort() and Arrays.binarySearch(). Students are given programming exercises to implement sorting and searching algorithms and use the built-in methods.

Uploaded by

gurusodhii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views11 pages

Searching and Sorting Programs

This document contains instructions for a lab on searching and sorting algorithms. It includes pseudocode and Java code examples for selection sort, bubble sort, linear search, and binary search algorithms. It also provides examples for using the built-in Java utility methods Arrays.sort() and Arrays.binarySearch(). Students are given programming exercises to implement sorting and searching algorithms and use the built-in methods.

Uploaded by

gurusodhii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

KING ABDULAZIZ UNIVERSITY

Faculty of Computing & Information Technology


Department of Computer Science

Lab Manual

CPCS204
Data Structures 1
1435/1436H

Lab - 3

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
2015 Lab-3: 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-3 1


Term I
2015 Lab-3: Searching and Sorting Algorithms

1) tage J (Journey)
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-3 2


Term I
2015 Lab-3: 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-3 3


Term I
2015 Lab-3: Searching and Sorting Algorithms

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-3 4


Term I
2015 Lab-3: 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

import java.util.Arrays;

public class binary_search {

//Answer task 2 here


public static int linearSearch(int[] number,int key)
{ int searchIndex=-1,i;
for (i = 0; i < number.length; i++)
{
if (number[i] == key) /* Searching element is present */
{searchIndex=i;
break;
}
}
if (i == number.length) /* Searching element is absent */
searchIndex=-1;
return searchIndex;

CPCS204 – The Lab Note Lab-3 5


Term I
2015 Lab-3: Searching and Sorting Algorithms
}

public static void main(String[] args) {


int ar1[]={2,44,5,66,78,90,23,66};
int p, key=78;

//Answer task 2 here


p= linearSearch(ar1,key);

//Answer task 3 here


p= Arrays.binarySearch(ar1,key) ;

System.out.println("element found at index "+p);

//Answer task 4 here


Arrays.sort(ar1);
p= Arrays.binarySearch(ar1,key) ;

System.out.println("element found at index "+p);


}
}

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.

//Answer task 1 here

import java.util.Arrays;

import java.util.Random;

/**program showing some Arrays library uses*/

CPCS204 – The Lab Note Lab-3 6


Term I
2015 Lab-3: Searching and Sorting Algorithms
public class ArrayTest {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

int num[]=new int[10];

Random rand=new Random(); //a pseudo-random number generator

rand.setSeed(System.currentTimeMillis()); //use current time


as a seed

//fill the num array with pseudo-random numbers from 0 to


99, inclusive

for(int i=0;i<num.length;i++)

num[i]=rand.nextInt(100);

int[] old= (int[]) num.clone(); //cloning the num array

System.out.println("arrays equal before sort:


"+Arrays.equals(old, num));

Arrays.sort(num); //sorting the num array (old is unchanged)

System.out.println("arrays equal after sort:


"+Arrays.equals(old, num));

System.out.println("Old ="+Arrays.toString(old));

System.out.println("num ="+Arrays.toString(num));

//Task2

//Answer task 2 here

int[] Arr= (int[]) old.clone(); //cloning the old array

Arrays.sort(Arr,5,10);

System.out.println("Arr ="+Arrays.toString(Arr));

CPCS204 – The Lab Note Lab-3 7


Term I
2015 Lab-3: Searching and Sorting Algorithms

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-3 8


Term I
2015 Lab-3: 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 enter a num[0]: 5
Please enter a num[1]: 6
Please enter a num[2]: 9
Please enter a num[3]: 7
Please enter a num[4]: 2
Please enter a num[5]: 4
Please enter a num[6]: 3
Please enter a num[7]: 8
Please enter a num[8]: 10
Please enter a num[9]: 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

CPCS204 – The Lab Note Lab-3 9


Term I
2015 Lab-3: Searching and Sorting Algorithms

salespeople earned salaries in each of the following ranges (assume that each
salesperson's salary is truncated to an integer amount):
$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-3 10

You might also like