Sorting and Searching PowerPoint PPT Presentation

presentation player overlay
1 / 4
About This Presentation
Transcript and Presenter's Notes

Title: Sorting and Searching


1
Sorting and Searching
  • Often with arrays it's more useful to return the
    index of an array element, rather than the
    elements value.
  • Ex if string name is an array of names of
    contest participants, and int score is an array
    of scores, such that participant namei has
    score scorei,
  • then knowing the value of the largest element in
    score won't tell who the winner is, but knowing
    the index of the largest element in score will.
  • int maxIndex(int A, int N)
  • int iMax 0
  • for(int i 1 i lt N i)
  • if (AiMax lt Ai)
  • imax i
  • return imax

2
Sorting using Selection Sort
  • Selection Sort is so named because it selects the
    largest of the remaining elements and puts it in
    its proper spot in the sorted array.
  • void selectionSort(int A, int N)
  • for(int length N length gt 1
  • length--)
  • int k maxIndex(A,length)
  • int temp Alength-1
  • Alength-1 Ak
  • Ak temp
  • // end for
  • // end selectionSort
  • 1st swap the largest element in the array with
    the last element of the array,
  • Then ignore the last array slot and move on to
    the largest element in the remainder of the array

int maxIndex(int A, int N) int iMax 0
for(int i 1 i lt N i) if (AiMax lt
Ai) imax i return imax // end
maxIndex
3
Searching
  • Consider searching for value x in an array A of N
    elements, and return the index of an element of A
    that matches the value x.
  • If no such element is found, an index of N is
    returned and, since it is not a valid index, the
    caller of the function can take to mean that no
    match was found.
  • For example, to search in an array of objects of
    type string, we can define the following
    function
  • int search(string A, int N, string x)
  • int i 0
  • while(i lt N Ai ! x)
  • i
  • return i / returns N or the index of the
    cell holding the value /
  • We might need to use a function match instead of
    to determine whether two objects match
  • int search(string A, int N, string x)
  • int i 0
  • while(i lt N !match(Ai,x))
  • i // need to define match()
  • return i

4
ICE Sorting by last, then first, name
  • Write a program that reads in a list of 10 names
    (first name followed by last name) and prints
    them out in the usual order - i.e. alphabetically
    by last name, using first names to break ties.

input Tina Tomalito John Maynor Dave Smith Bill
Smith Andy Ahern
output Ahern, Andy Maynor, John Smith, Bill
Smith, Dave Tomalito, Tina
Write a Comment
User Comments (0)
About PowerShow.com