Sorting and Searching. Problem Read in a parameter value n, then read in a set of n numbers. Print the numbers in their original order. Sort the numbers.

Slides:



Advertisements
Similar presentations
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Advertisements

CSE Lecture 3 – Algorithms I
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Programming Searching Arrays. COMP102 Prog. Fundamentals: Searching Arrays/ Slide 2 Copyright © 2000 by Broks/Cole Publishing Company A division of International.
Computation for Physics 計算物理概論 Algorithm. An algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing,
Arrays Arrays are data structures consisting of data items of the same type. Arrays are ‘static’ entities, in that they remain the same size once they.
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
Searching Arrays. COMP104 Lecture 22 / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and return its index if the.
C++ Plus Data Structures
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
CS 1400 March 30, 2007 Chapter 8 Searching and Sorting.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Searching Arrays Linear search Binary search small arrays
Searching and Sorting Arrays
Programming Sorting Arrays. COMP104 Lecture 25 / Slide 2 Sorting l To arrange a set of items in sequence. l It was estimated that 25~50% of all computing.
Searching Arrays. COMP104 Array Sorting & Searching / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and save its.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Chapter 8 ARRAYS Continued
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.
EENG212 Algorithms and Data Structures
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
Starting Out with C++, 3 rd Edition 1 Searching an Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
February 4, 2005 Searching and Sorting Arrays. Searching.
Lecture 16: Searching and Sorting Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
Array & Matrix Selected topics. 1. It will compare two adjacent elements, if second element is smaller than the first then it will swap them, if we wanted.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
CS 162 Intro to Programming II Bubble Sort 1. Compare adjacent elements. If the first is greater than the second, swap them. Do this for each pair of.
Sorting & Searching Review. Selection Sort 1. Find the smallest element 2. Move to the front of the array (swap with front) 3. Repeat Steps 1&2, but ignoring.
ALGORITHMS.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
1 Principles of Computer Science I Honors Section Note Set 5 CSE 1341.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Elementary Sorting 30 January Simple Sort // List is an array of size == n for (i = 1; i < n; i++) for (j = i+1; j List[j])
Sorting and Searching. Searching  Problem definition: Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Data Structures Arrays and Lists Part 2 More List Operations.
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Searching Arrays Linear search Binary search small arrays
Searching and Sorting Algorithms
Sorting Why? Displaying in order Faster Searching Categories Internal
Lecture 14 Searching and Sorting Richard Gesick.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
Lecture 11 Searching and Sorting Richard Gesick.
24 Searching and Sorting.
Searching.
Module 8 – Searching & Sorting Algorithms
ADT LIST So far we have seen the following operations on a “list”:
Presentation transcript:

Sorting and Searching

Problem Read in a parameter value n, then read in a set of n numbers. Print the numbers in their original order. Sort the numbers into ascending order. Finally, print the numbers in sorted order. Original Order Sorted Order

The Linear or Selection Sort Initialize an array with the numbers to be sorted Hold the leftmost position (index 0) and compare the value in that position to each of the values in the other positions, one at a time When the value in position 0 is greater than the compared value, swap the numbers Pass 0 (0-1) (45,23) swap (0-2) (23,18) swap (0-3) (18,0) swap After this pass, the smallest number is in the leftmost position. Now fix the leftmost position plus 1 (index 1) and compare the value in that position to each of the other positions, one at a time When the value in position 1 is greater than the compared value, swap the numbers Repeat this process for index 2, 3, etc until the next to last index When completed, the number will be sorted in ascending order

The Linear or Selection Sort for each position in the array (except the last) for each candidate for that position, compare the candidate to the element currently in that position if the candidate is smaller swap them /* Function linearsort() * Input: * numb - array to be sorted * n - number of elements to sort * Process: linear sort * Output: numb sorted into ascending order */ void linearsort(int numb[], int n) { int temp; for (int pass = 0; pass < (n-1); pass++) for (int cand = (pass+1); cand < n; cand++) if (numb[pass] > numb[cand]) { temp = numb[pass]; numb[pass] = numb[cand]; numb[cand] = temp; } return; }

Tracing the Selection Sort #include using namespace std; void linearsort(int[], int); void printArray(int [], int); int main(){ int numb[]={98, 23, 13, 2, 0, 210, 45, 87, 65, 23, 100, -1}; printArray(numb,12); linearsort(numb,12); printArray(numb,12); system("pause"); return 0; } void printArray(int numb[], int n) { for (int i=0; i<n; i++) cout<<numb[i]<<" "; cout<<endl; } void linearsort(int numb[], int n) { int temp; for (int pass = 0; pass < (n-1); pass++) for (int cand = (pass+1); cand < n; cand++) if (numb[pass] > numb[cand]) { temp = numb[pass]; numb[pass] = numb[cand]; numb[cand] = temp; cout<<"pass "<<pass<<" cand "<<cand<<": "; printArray(numb,n); } return; }

The Linear or Selection Sort pass 0 cand 1: pass 0 cand 2: pass 0 cand 3: pass 0 cand 4: pass 0 cand 11: pass 1 cand 2: pass 1 cand 3: pass 1 cand 4: pass 1 cand 11: pass 2 cand 3: pass 2 cand 4: pass 2 cand 11: pass 3 cand 4: pass 3 cand 11: pass 4 cand 6: pass 4 cand 9: pass 5 cand 6: pass 5 cand 7: pass 5 cand 8: pass 5 cand 9: pass 5 cand 11: pass 6 cand 7: pass 6 cand 8: pass 6 cand 9: pass 6 cand 11: pass 7 cand 8: pass 7 cand 9: pass 7 cand 11: pass 8 cand 9: pass 8 cand 11: pass 9 cand 10: pass 9 cand 11: pass 10 cand 11:

The Bubble Sort Compares adjacent pairs of numbers instead of fixing a position and comparing the candidates to it as in the linear sort After the first pass, the largest number is in the rightmost position After each subsequent pass, the largest number remaining is in the rightmost position that has not been already fixed

The Bubble Sort do the following as long as there has been a swap on the last pass for each element of the array compare the element to its neighbor if they are out of order swap them /* Function bubblesort() * Input: * numb - array to be sorted * n - number of elements to sort * Process: * bubble sort * Output: * numb sorted into ascending order */ See const int TRUE = 1; const int FALSE = 0; void bubblesort(int numb[], int n) { int swapped; int temp; do { swapped = FALSE; // initialize swapped to FALSE for (int pos = 0; pos < (n-1); pos++) if (numb[pos] > numb[pos+1]) { temp = numb[pos]; numb[pos] = numb[pos+1]; numb[pos+1] = temp; // indicate swap has occurred swapped = TRUE; } } while (swapped); return; }

The Bubble Sort pos 0: pos 1: pos 2: pos 3: pos 5: pos 6: pos 7: pos 8: pos 9: pos 10: pos 0: pos 1: pos 2: pos 4: pos 5: pos 6: pos 7: pos 9: pos 0: pos 1: pos 5: pos 6: pos 8: pos 0: pos 5: pos 7: pos 4: pos 6: pos 5: pos 4: pos 3: pos 2: pos 1: pos 0: const int TRUE = 1; const int FALSE = 0; void bubblesort(int numb[], int n) { int swapped; int temp; do { swapped = FALSE; // initialize swapped to FALSE for (int pos = 0; pos < (n-1); pos++) if (numb[pos] > numb[pos+1]) { temp = numb[pos]; numb[pos] = numb[pos+1]; numb[pos+1] = temp; // indicate swap has occurred swapped = TRUE; } } while (swapped); return; }

Sorting an Array of Strings #include using namespace std; const int SIZE = 5; int main() { string str[SIZE]; string tempstr; str[0] = "Jones"; str[1] = "Harrow"; str[2] = "Tenenbaum"; str[3] = "Arnow"; str[4] = "Raphan"; //print the original array cout << "Original Array" << endl; for (int i = 0; i < SIZE; i++) cout << str[i] << endl; // sort the array for (int pos = 0; pos < SIZE-1; pos++) for (int cand = pos+1; cand < SIZE; cand++) if (str[cand] < str[pos]) { tempstr = str[cand]; str[cand] = str[pos]; str[pos] = tempstr; } //print the sorted array cout << endl << "Sorted Array" << endl; for (int i = 0; i < SIZE; i++) cout << str[i] << endl; return 0; } Original Array Jones Harrow Tenenbaum Arnow Raphan Sorted Array Arnow Harrow Jones Raphan Tenenbaum

Sorting an Array of Strings in a Function cout << "Original Array" << endl; for (int i = 0; i < SIZE; i++) cout << str[i] << endl; // sort the array sortthearray(str); //print the sorted array cout << endl << "Sorted Array" << endl; for (int i = 0; i < SIZE; i++) cout << str[i] << endl; void sortthearray(string str[]) { string tempstr; // sort the array for (int pos = 0; pos < SIZE-1; pos++) for (int cand = pos+1; cand < SIZE; cand++) if (str[cand] < str[pos]) { tempstr = str[cand]; str[cand] = str[pos]; str[pos] = tempstr; } return; }

Searching Problem: We have an array of values: Search for 99 and 77 If found, return the position of the value within the array If not found, return -1

Linear Search for each position in the array compare the element in that position to the search value if they are equal return the position in the array if no element is equal to the search value return a failure signal (-1) /* Function linearsearch() * Input: * numb - array to be searched * n - number of elements in the array * searchvalue - the value to search for * Process: * linear search * Output: * returns the position of searchvalue in the array * returns -1 if searchvalue not found */ int linearsearch(int numb[], int n, int searchnumber) { for (int position = 0; position < n; position++) if (numb[position] == searchnumber) return (position); // search value found return (-1); // search value not found }

Binary Search of Sorted Array Pseudocode for Binary Search: low = 0; high = n-1; while (low <= high) look at the element halfway between low and high if the element equals the search value return its position else if the element is larger than the search value high = the tested position - 1 else low = tested position + 1 NOTE: To do a binary search of an array, the numbers must be in sorted order

Binary Search of Sorted Array For example, consider the following sequence of integers sorted in ascending order and say we are looking for the number 55: Initially, the search space contains indices 1 through 11. Store two numbers, the low and high indices. Choose the median value, which is the value at index 6 (the midpoint between 1 and 11): this value is 41 and it is smaller than the target value. From this we conclude not only that the element at index 6 is not the target value, but also that no element at indices between 1 and 5 can be the target value, because all elements at these indices are smaller than 41, which is smaller than the target value. This brings the search space down to indices 7 through 11: Proceeding in a similar fashion, we chop off the second half of the search space and are left with: Depending on how we choose the median of an even number of elements we will either find 55 in the next step or chop off 68 to get a search space of only one element. Either way, we conclude that the index where the target value is located is 7.

Comparison of Search Algorithms Average number of tries using linear search Maximum number of tries using binary search List sizeLocateRejectLocateReject , , ,000,000500,0001,000,00020

Binary Search of Sorted Array /* Function binarysearch() * Input: * numb - array to be searched * n - number of elements in the array * searchvalue - the value to search for * Process: binary search * Output: * returns the position of searchvalue in the array * returns -1 if searchvalue not found */ int binarysearch(int numb[], int n, int searchnumber) { int low,high,test; low = 0; high = n - 1; while (low <= high) { test = (low + high) / 2; if (numb[test] == searchnumber) return (test); // search value found else if (numb[test] > searchnumber) high = test - 1; else low = test + 1; } return (-1); // search value not found }