Presentation is loading. Please wait.

Presentation is loading. Please wait.

Search,Sort,Recursion.

Similar presentations


Presentation on theme: "Search,Sort,Recursion."— Presentation transcript:

1 Search,Sort,Recursion

2 Searching, Sorting and Recursion
Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search

3

4 Searching Arrays A sequential search is one way to search an array for a given value known as the target or key Algorithm Look at each element from first to last to see if the target value is equal to any of the array elements Return the index of the target value to indicate where the target was found in the array Return a value of -1 if the value was not found

5 The search Function The search function of Display 7.10…
Uses a while loop to compare array elements to the target value Sets a variable of type bool to true if the target value is found, ending the loop Checks the boolean variable when the loop ends to see if the target value was found Returns the index of the target value if found, otherwise returns -1

6

7 Linear Search Let’s try this example:
int array[8] = { 6, 4, 1, 9, 7, 3, 2, 8 }; Let’s say we have to find value 3 in the array, how do we use a linear search for this? Compare each element with the target value 3. If any element of the array matches, return the index of the element. If no element of the array matches, return -1.

8 Pseudocode for Linear Search
For each element in the list do If the current element is the same as the target, return the index of the current element If the entire list was searched and the target wasn’t found, return -1 .What is the worst case scenario? Need to search all a[0]..a[n] elements before target is not found. What is the best case scenario? Need to search only a[0] before target is found.

9

10 Search – two implementations
int search(int array[], int size, int target) { int index = 0; bool found = false; while ((!found) && (index < size)) { if (target == array[index]) found = true; else index++; } if (found) return index; else return -1; int search(int array[], int size, int target) { for(int index = 0;index < size; index++) if (target == array[index]) return index; } return -1;

11

12 Exercise Write a program that will read up to 10 letters into an array and write the letters back to the screen in the reverse order? abcd should be output as dcba Use a period as a sentinel value to mark the end of input

13 Inserting into an array
Arrays are great for keeping unordered lists of values. But what if you want an ordered list of values? You can sort the values in an array using a sort function. Or you can place them into the array in sorted order. If you want to place them in sorted order, you need to be able to insert a new value in the correct position. Let’s assume you know how to find the position for insertion.

14 Inserting into an Array
Recall that an array is just a collection that is kept in sequential memory. int array[20] = { 1, 3, 6, 7, 10 }; Recall that an initializer that specifies fewer values than the array capacity initializes the remaining cells to 0 of the base type. Let’s say we want to insert the value 4 in the 3rd position without losing the values larger than 4. What do we have to do?

15 We have to make room for the new value by pushing the other values down 1 position.
As long as there is CAPACITY, we can start at the end and move the contents down 1. We do that in a loop that starts at the end and goes back towards the insertion position.

16 Pseudocode - Insert a value into an Array
Is there enough room for another value? Test if increasing Number Of Elements by 1 will be greater than the Capacity. If the array is full, fail gracefully. That will depend on the return type. Failing gracefully: If the return type is void, just return and do nothing. If the return type is bool, return false. If the return type is int, return -1. For each element starting from the last element (i.e. number of elements – 1) until we reach the insert position, do array[i+1] = array[i] Increase the size of number of elements by 1.

17 Deleting an element from an Array
Check that the position given for deletion is within the valid range. What is the valid range? The valid range is from 0 to number of elements – 1. If the position is not in range, fail gracefully. For each element starting from the index of the delete position, do array[i] = array[i+1] Decrease the size of number of elements.

18 Program Example: Sorting an Array
Sorting a list of values is very common task Create an alphabetical listing Create a list of values in ascending order Create a list of values in descending order We already saw Selection sort Recall that for each position, traverse the rest of the array to find the minimum value and swap it with the current value. Many sorting algorithms exist Some are very efficient Some are easier to understand

19 Program Example: The Selection Sort Algorithm
When the sort is complete, the elements of the array are ordered such that a[0] < a[1] < … < a [ number_used -1] Outline of the algorithm for (int index = 0; index < number_used; index++) place the index-th smallest element in a[index]

20 Program Example: Sort Algorithm Development
One array is sufficient to do our sorting Search for the smallest value in the array Place this value in a[0], and place the value that was in a[0] in the location where the smallest was found Starting at a[1], find the smallest remaining value swap it with the value currently in a[1] Starting at a[2], continue the process until the array is sorted Display 7.11 Display 7.12 (1-2)

21 Display 7.11

22 Selection sort Remember the Outline of the algorithm
for (int index = 0; index < number_used; index++) place the index-th smallest element in a[index]; Write a function to return the index of the smallest int index_of_min(int array[], int num_used, int start) { int min_index = start; for (int i = start+1; i < num_used; i++) if (array[i] < array[min_index]) min_index = i; return min_index; }

23 BubbleSort Goal: order the array from smallest to largest
Loop through the entries If the current value is greater than the next one, swap them If ANY swaps happened, need to loop through all over again!

24 Bubble Sort Another algorithm for sorting arrays.
Compare each pair of adjacent array elements, if they are in the wrong order, swap them. Continue until the array is sorted. Bubble sort is named for what happens with soda. The light bubbles float to the top, the heavy soda floats to the bottom.

25

26

27

28

29

30

31

32

33

34 Sort – by Hand RandArray 46 48 29 69 81 19 26 77 14 85 2 SortedArray
index 1 3 4 5 6 7 8 9 10 11 SortedArray

35 Lab 11: Bubble Sort void bubbleSort(int A[],int arraySize) { bool did1swap; // indicates that we need to go through again do { did1swap = false; // go through all elements, compare each item & the one higher for (int i = 0; i < arraySize - 1; i++) //stop before the top if (A[i] > A[i + 1]) { // if one is out of order, then swap(A[i], A[i + 1]); // swap them did1swap = true;// need another run } } while (did1swap == true);

36 Bubble Sort Performance
How many times does a bubble sort traverse the array? Standard Bubble sort always takes O(N*N) time for an array of size N. Bubble sort is not efficient, it is easy to implement and understand. How can bubble sort be made a little more efficient? Stop sorting if a pass makes no swaps.

37

38 Binary Search Algorithm
int binary_search(int array[], int size, int search) { // array is sorted in ascending order int first = 0; int last = size-1; int middle = (last+first)/2; // divide the array into two parts while (first <= last) { if (array[middle] < search) // it’s in the bigger half { first = middle + 1; } else if (array[middle] == search) return middle; // found it else // it’s in the smaller half. last = middle - 1; middle = (last+first)/2; // divide the array into two parts return -1; Binary Search Algorithm

39 Recursion When a function calls itself:
Can be a simpler way to write a loop Can be used as a 'divide-and-conquer' method

40 Power calculation, another way to look at it
2 5 = 2 * 2 * 2 * 2 * 2 We can also say 2 5 = 2 * 2 4 And we know: 2 0 = 1

41 Alternate power (pow) function 𝑏𝑎𝑠𝑒 𝑒𝑥𝑝
int power(int base, int expon) { if(expon>0) return (base * power(base,expon-1)); else return 1; // any base with 0 as exponent = 1 } Recursive case Stop (base) case

42 Recursive function design
Must have: Stopping case, sometimes called 'base case' Simplified recursive calls – each new call must bring us closer to reaching base case(s) – these are the ‘recursive cases’.

43 Recursive Binary Search
int binary_search(int array[], int first, int last, int search) {// array is sorted in ascending order int middle = (last+first)/2; // divide the array into two parts if (first <= last) { if (array[middle] < search) { // it’s in the bigger half return binary_search(array, middle+1, last, search); } else if (array[middle] == search) { return middle; else { return binary_search(array, first, middle-1, search); } else { return -1;

44 Recursion A problem that can be solved by dividing it into smaller and smaller ‘like’ pieces. At least one recursive case that breaks the problem into smaller piece At least one base case that stops the recursion. In Computer Science, a recursive function is a function that calls itself until it gets to a boundary case and then completes the computation as it unwinds. Examples of recursive problems: The factor function from the t leomework is recursive Factorial and Fibonacci are naturally recursive as are tree searches. Recursion is extremely inefficient. Only use it if you must.


Download ppt "Search,Sort,Recursion."

Similar presentations


Ads by Google