DATA STRUCTURE CSC 212 REEM ALMOTIRI Information Technology Department Majmaah University 1 Lecture 2 Searching and Sorting Arrays 2 Topics What is Searching Linear Searching Algorithms Binary Search Algorithm What is Sorting Types of Sorting Algorithms 9-3 What is Searching Search: locate an item in a list (array, vector, etc.) of information Searching :-is the process of determining whether or not a given value exists in a data structure or a storage media. We discuss two searching methods on one - dimensional arrays:- – Linear search – Binary search 4 Linear Searching Algorithms Suppose that you want to determine whether 27 is in the list First compare 27 with list[0]; that is, compare 27 with 35 Because list[0] ≠ 27, you then compare 27 with list[1] Because list[1] ≠ 27, you compare 27 with the next element in the list Because list[2] = 27, the search stops This search is successful! Figure 1: Array list with seven (07) elements 5 Linear Searching Algorithms int linearSearch(const int integerArray[],int SIZE,int value) { int index = 0; int position1 = -1; bool foundNum = false; while(index < SIZE) { if(integerArray[index] == value) { foundNum = true; position1 = index; } index++; } return position1; } 6 Linear Search Algorithm Set found to false Set position to –1 Set index to 0 While index < number of elts and found is false If list [index] is equal to search value found = true position = index End If Add 1 to index End While Return position 9-7 Linear Search Example Array numlist contains 17 23 5 11 2 29 3 Searching for the value 11, linear search examines 17, 23, 5, and 11 Searching for the the value 7, linear search examines 17, 23, 5, 11, 2, 29, and 3 9-8 Linear Search Tradeoffs Benefits Easy algorithm to understand Array can be in any order Disadvantage 9-9 Inefficient (slow): for array of N elements, examines N/2 elements on average for value that is found in the array, N elements for value that is not in the array Binary Search Algorithm Can only be performed on a sorted list !!! Uses divide and conquer technique to search list Divide a sorted array into three sections: 1. middle element elements on one side of the middle element elements on the other side of the middle element 2. 3. If the middle element is the correct value, done. Otherwise, go to step 1, using only the half of the array that may contain the correct value. Continue steps 1 and 2 until either the value is found or there are no more elements to examine. 9-10 Binary Search Algorithm Search item is compared with middle element of list 1. If search item < middle element of list, search is restricted to first half of the list 2. If search item > middle element of list, search second half of the list 3. If search item = middle element, search is complete 9-11 Binary Search Example Array numlist2 contains 2 3 5 11 17 23 29 Searching for the the value 11, binary search examines 11 and stops Searching for the the value 7, binary search examines 11, 3, 5, and stops 9-12 Binary Search Tradeoffs Benefit Much more efficient than linear search (For array of N elements, performs at most log2N comparisons) Disadvantage 9-13 Requires that array elements be sorted Binary Search Algorithm example • Determine whether 75 is in the list Figure 2: Array list with twelve (12) elements Figure 3: Search list, list[0] … list[11] 14 Binary Search Algorithm example Figure 4: Search list, list[6] … list[11] 15 Binary Search Algorithm int binarySearch(const int integerArray[],int size,int value) { int first = 0; int last = size-1; int midpoint = (first+last)/2; int position2 = -1; bool foundNum = false; while(!foundNum && first<=last) { if(integerArray[midpoint] == value) { foundNum = true; position2++; return position2; } else if(integerArray[midpoint] > value) { last = midpoint-1; position2++; } else last = midpoint+1; position2++; } return position2; } 16 Searching an Array of Objects 9-17 Search algorithms are not limited to arrays of integers When searching an array of objects or structures, the value being searched for is a member of an object or structure, not the entire object or structure Member in object/structure: key field Value used in search: search key What is Sorting Sort: arrange values into an order Given a set (container) of n elements E.g. array, set of words, etc. Goal Arrange the elements in ascending order 9-18 Alphabetical Ascending numeric Descending numeric Start 1 23 2 56 9 8 10 100 End 1 2 8 9 10 23 56 100 Types of Sorting Algorithms There are many, many different types of sorting algorithms, but the primary ones are: Bubble Sort Selection Sort Insertion Sort 19 Bubble Sort Algorithm Algorithm :1. 2. 3. 4. 9-20 Compare 1st two elements and exchange them if they are out of order. Move down one element and compare 2nd and 3rd elements. Exchange if necessary. Continue until end of array. Pass through array again, repeating process and exchanging as necessary. Repeat until a pass is made with no exchanges. Bubble Sort Example Array numlist3 contains 17 Compare values 17 and 23. In correct order, so no exchange. 23 5 11 Compare values 23 and 11. Not in correct order, so exchange them. Compare values 23 and 5. Not in correct order, so exchange them. 9-21 Bubble Sort Example (continued) After first pass, array numlist3 contains In order from previous pass 17 Compare values 17 and 5. Not in correct order, so exchange them. 5 11 23 Compare values 17 and 23. In correct order, so no exchange. Compare values 17 and 11. Not in correct order, so exchange them. 9-22 Bubble Sort Example (continued) After second pass, array numlist3 contains In order from previous passes 5 Compare values 5 and 11. In correct order, so no exchange. 11 17 23 Compare values 17 and 23. In correct order, so no exchange. Compare values 11 and 17. In correct order, so no exchange. 9-23 No exchanges, so array is in order Bubble Sort Tradeoffs Benefit Easy to understand and implement Disadvantage Inefficiency makes it slow for large arrays 9-24 Bubble Sort 7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8 2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8 2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 2 7 5 8 4 2 5 4 7 8 2 7 5 4 8 25 (done) Bubble Sort void bubbleSort(int arr[], int n) { bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < n - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } 26 Selection sort The idea of algorithm is quite simple. Array is imaginary divided into two parts: - sorted one and unsorted one. At the beginning, sorted part is empty, while unsorted one contains whole array. At every step, algorithm finds minimal element in the unsorted part and adds it to the end of the sorted one. When unsorted part becomes empty, algorithm stops. 27 Selection Sort Algorithm 1. Locate smallest element in array and exchange it with element in position 0. 2. Locate next smallest element in array and exchange it with element in position 1. 3. Continue until all elements are in order. 9-28 Selection Sort Example Array numlist contains 11 2 29 3 Smallest element is 2. Exchange 2 with element in 1st array position (i.e. element 0). Now in order 9-29 2 11 29 3 Selection Sort – Example (continued) Next smallest element is 3. Exchange 3 with element in 2nd array position. Now in order 2 3 29 11 Next smallest element is 11. Exchange 11 with element in 3rd array position. Now in order 9-30 2 3 11 29 Selection sort Given an array of length n, Search elements 0 through n-1 and select the smallest Swap it with the element in location 0 Search elements 1 through n-1 and select the smallest Swap it with the element in location 1 Search elements 2 through n-1 and select the smallest Swap it with the element in location 2 Search elements 3 through n-1 and select the smallest Swap it with the element in location 3 Continue in this fashion until there’s nothing left to search 31 Selection sort 7 2 8 5 4 2 7 8 5 4 2 4 8 5 7 2 4 5 8 7 2 4 5 7 8 32 Selection sort void selectionSort(int arr[], int n) { int i, j, minIndex, tmp; for (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[minIndex]) minIndex = j; if (minIndex != i) { tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; } } } 33 Selection Sort Tradeoffs Benefit More efficient than Bubble Sort, due to fewer exchanges Disadvantage Considered harder than Bubble Sort to understand 9-34 Insertion sort Insertion sort algorithm resembles selection sort. Array is imaginary divided into two parts - sorted one and unsorted one. At the beginning, sorted part contains first element of the array and unsorted one contains the rest. At every step, algorithm takes first element in the unsorted part and inserts it to the right place of the sorted one. When unsorted part becomes empty, algorithm stops. 35 Insertion sort : 36 Insertion sort : void insertionSort(int arr[], int length) { int i, j, tmp; for (i = 1; i < length; i++) { j = i; while (j > 0 && arr[j - 1] > arr[j]) { tmp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = tmp; j--; } } } 37 Sorting an Array of Objects As with searching, arrays to be sorted can contain objects or structures The key field determines how the structures or objects will be ordered When exchanging contents of array elements, entire structures or objects must be exchanged, not just the key fields in the structures or objects 9-38 HOMEWORK! 1-39