1 / 62

Linear Search in a Sorted Array

Linear Search in a Sorted Array. Problem: Find the index of a number in a sorted array of integers. LinearSearch_InSortedArray.c. #include <stdio.h> #include <stdlib.h> #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91};

eze
Télécharger la présentation

Linear Search in a Sorted Array

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linear Search in a Sorted Array

  2. Problem: Find the index of a number in a sorted array of integers

  3. LinearSearch_InSortedArray.c #include <stdio.h> #include <stdlib.h> #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; int target = 62; //int target = 72;// Try this target next int i, idx=-1; for(i=0; i< N; i++) { if(a[i] == target) { idx=i; break; } else if(a[i]>target) break; // we can stop here } if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d. \n\n", idx); }

  4. Analysis • If the list is unsorted we have to search all numbers before we declare that the target is not present in the array. • Because the list is sorted we can stop as soon as we reach a number that is greater than our target • Can we do even better?

  5. Binary Search • At each step it splits the remaining array elements into two groups • Therefore, it is faster than the linear search • Works only on an already SORTED array • Thus, there is a performance penalty for sorting the array [http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm]

  6. Example:SuccessfulBinarySearch [http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm]

  7. Example: BinarySearch.c

  8. Binary_Search.c #include <stdio.h> #include <stdlib.h> #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; //sorted in increasing order int i; int target = 22; //int target = 72; // Try this target next int idx=-1; // if the target is found its index is stored here int first=0; // initial values for the three search varaibles int last= N-1; int mid= (first + last)/2; while(last >= first) { if( a[mid] == target) { idx=mid; // Found it! break; // exit the while loop } else if(a[mid] > target) { // don't search in a[mid] ... a[last] last = mid-1; } else { // don't search in a[first] ... a[mid] first = mid +1; } // recalculate mid for the next iteration mid = (first + last)/2; // integer division! } // end of while loop if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d \n\n", idx); }

  9. Analysis of Searching Methods • For an array of size n • Sequential Search (Average-Case) n/2 • Sequential Search (Worst-Case) n • Binary Search (Average-Case) log(n)/2 • Binary Search (Worst-Case) log(n)

  10. Other Stuff in Chapter 8

  11. Two-Dimensional Arrays • int Matrix[2][3]; • Defines the following elements: • Row1: Matrix[0][0], Matrix[0][1], Matrix[0][2] • Row2: Matrix[1][0], Matrix[1][1], Matrix[1][2]

  12. Two-Dimensional Arrays int Matrix[2][3]; • Initialization: Matrix[0][0]=3; Matrix[0][1]=4; Matrix[0][2]=5; Matrix[1][0]=1; Matrix[1][1]= -20; Matrix[1][2]=7;

  13. Two-Dimensional Arrays • Initialization when defined: int Matrix[2][3] = { {3, 4, 5}, {1, -20, 7}};

  14. Two-Dimensional Arrays • 2D arrays and nested for loop int Matrix[2][3] = { {3, 4, 5}, {1, -20, 7}}; int i,j; for(i=0; i< 2; i++) { for(j=0; j<3; j++) printf(“%3d ”, Matrix[i][j]); printf(“\n”); }

  15. Sorting Algorithms

  16. Chapter 8 (Sorting)

  17. Insertion Sort 0 [http://web.ics.purdue.edu/~cs154/lectures/lecture010.htm]

  18. Analogy: Sorting Cards

  19. Analogy: Sorting Cards

  20. First Iteration First Iteration(All face up cards are sorted. End of the first iteration.)

  21. Second Iteration Second Iteration(All face up cards are sorted. End of the second iteration.)

  22. Third Iteration Third Iteration(All face up cards are sorted. End of the third iteration.)

  23. Fourth Iteration Fourth Iteration(All face up cards are sorted. End of the fourth iteration.)

  24. Fifth Iteration Fifth Iteration(All face up cards are sorted. End of the fifth iteration.)

  25. Swapping Array Elements [http://www.scs.ryerson.ca/jpanar/w2006/cps125/example.gifs/ch7/Arr.Swap.gif]

  26. First Iteration (array-like swapping) First Iteration(All face up cards are sorted. End of the first iteration.)

  27. Second Iteration (array-like swapping) Second Iteration(All face up cards are sorted. End of the second iteration.)

  28. Example:InsertionSort [http://web.ics.purdue.edu/~cs154/lectures/lecture010.htm]

  29. Animations for Insertion Sort [http://maven.smith.edu/~thiebaut/java/sort/demo.html]

  30. Animations of Sorting Algoritms • http://maven.smith.edu/~thiebaut/java/sort/demo.html • http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html

  31. C code // Swap a[i] with the smallest element int temp = a[i]; a[i] = a[minIndex];a[minIndex] = temp;

  32. Example: InsertionSort.c

  33. // Insertion Sort #include <stdlib.h> #define N 6 int main() { int a[N]= { 23, 78, 45, 8, 32, 56}; int i; for(i = 1; i < N; i++) { int j = i; int INS = a[i]; while ((j > 0) && (a[j-1] > INS)) { a[j] = a[j-1]; // shift elements to the right j--; } a[j] = INS; // insert the element } system("pause"); }

  34. Selection Sort(Cards Example)

  35. Initial Configuration(search all cards and find the largest)

  36. Swap the two cards

  37. As before, the swap is performed in three steps.

  38. Among the remaining cards the king is the largest. It will remain in place. But the algorithm may perform Some empty operations (ie., swap it with itself in place) Sorted Unsorted

  39. Among the remaining cards the queen is the largest. It will remain in place. But the algorithm may perform Some empty operations (i.e., swap it with itself in place) Sorted Unsorted

  40. Among the remaining cards the Jack is the largest. It will remain in place. But the algorithm may perform Some empty operations (i.e., swap it with itself in place) Sorted Unsorted

  41. As before, the swap is performed in three steps.

  42. We are down to the last card. Because there is only one and Because we know that it is Smaller than all the rest We don’t need to do anything Else with it. This is why the Algorithm goes up to < N-1 Sorted Unsorted

  43. All cards are now sorted. Sorted

  44. Selection Sort [http://web.ics.purdue.edu/~cs154/lectures/lecture010.htm]

  45. Example:SelectionSort [http://web.ics.purdue.edu/~cs154/lectures/lecture010.htm]

  46. Example: SelectionSort.c

  47. // Selection Sort #include <stdlib.h> #define N 6 int main() { int a[N]= { 23, 78, 45, 8, 32, 56}; int i,j; // Sort the array using Selection Sort int minIndex; for(i=0; i < N-1; i++) { // find the minimum element in the unsorted part of the array minIndex=i; for(j=i+1; j < N; j++) if(a[j] < a[minIndex]) minIndex = j; // Swap a[i] with the smallest element int temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp; } system("pause"); }

  48. Bubble Sort(Cards Example)

  49. Initial Configuration Unsorted

  50. First iteration of the outer loop

More Related