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 Let’s submit it!

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

4

5 Searching Arrays A sequential search is one way to search an array for a given value Look at each element from first to last to see if the target value is equal to any of the array elements The index of the target value can be returned to indicate where the value was found in the array A value of -1 can be returned if the value was not found

6 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

7

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

9 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.

10

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 = array[start]; for (int i = start+1; i < num_used; i++) if (array[i] < min) min = array[i]; return min; }

23 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.

24

25

26

27

28

29

30

31

32

33 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.

34

35 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

36 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;

37 Recursion A problem that can be solved by dividing it into smaller and smaller ‘like’ pieces. 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 homework 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