Sort and Search in Data Structure
Sort and Search in Data Structure
! Given an array of items, arrange the items so that they are sorted from smallest to largest. ! Select next item, in turn, that will be appended to the sorted part of the array:
Scan the array to find the smallest value, then swap this value with the value at cell 0. ! Scan the remaining values (all but the first value), to find the next smallest, then swap this value with the value at cell 1. ! Scan the remaining values (all but the first two) to find the next smallest, then swap this value with the value at cell 2. ! Continue until the array is sorted.
!
Summer 2010
15-110 (Reid-Miller)
[1] 1 5 5 2 2 2 2 2
[2] 3 3 3 3 3 3 3 3
[3] 7 7 7 7 7 7 7 5
[4] 2 2 2 5 5 5 5 7 find min swap to index 0 find min swap to index 1 find min swap to index 2 find min swap to index 3
15-110 (Reid-Miller)
}!
Summer 2010
15-110 (Reid-Miller)
Lexicographical ordering
! The String class compareTo method compares two strings lexicographically, which is similar to alphabetically except that it includes digits and other symbols:
! ! !
Space comes before digits Digits come before uppercase letters Uppercase letters come before lower case letters
! Example: The following are in lexicographical order: "01234" "012AB" "ABC" "ABC D" "ABCD"! "XYZ" "XyZ" "abc" "bc"!
Summer 2010 15-110 (Reid-Miller) 6
! How would you write a compareTo method for the Date class?!
Summer 2010 15-110 (Reid-Miller) 8
!public int compareTo(Date other) {! !! if (this.year != other.year)! !! return this.year - other.year;! !! else if (this.month != other.month)! !! return this.month - other.month;! !! else! !! return this.day - other.day;! !}!
Summer 2010
15-110 (Reid-Miller)
Summer 2010
15-110 (Reid-Miller)
10
Summer 2010
15-110 (Reid-Miller)
13
15-110 (Reid-Miller)
Summer 2010
15-110 (Reid-Miller)
16
Summer 2010
15-110 (Reid-Miller)