SlideShare une entreprise Scribd logo
1  sur  58
Télécharger pour lire hors ligne
Chapter 11 Sorting and Searching
Chapter 10 Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Searching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Search Result number Unsuccessful Search: Successful Search: 23 17 5 90 12 44 38 0 1 2 3 4 5 6 7 8 84 77 NOT_FOUND search( 45 ) search( 12 ) 4
Linear Search ,[object Object],public   int  linearSearch  (   int []  number,  int  searchValue  ) { int   loc = 0; while   ( loc < number.length  &&  number[loc] != searchValue ) { loc++; } if   ( loc == number.length )   {   //Not found return  NOT_FOUND;  }   else   { return  loc;   //Found, return the position } }
Linear Search Performance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Binary Search ,[object Object],[object Object],number 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90
Sequence of Successful Search - 1 search( 44 ) low high mid 38 <  44 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high low low = mid+1 = 5 mid 4
Sequence of Successful Search - 2 search( 44 ) low high mid 44  < 77 4 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high = mid-1=5 mid 6 high low 5 8 #2
Sequence of Successful Search - 3 search( 44 ) low high mid 44  == 44 4 6 Successful Search!! 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 high low 5 5 #3 mid 5
Sequence of Unsuccessful Search - 1 search( 45 ) low high mid 38 <  45 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high low low = mid+1 = 5 mid 4
Sequence of Unsuccessful Search - 2 search( 45 ) low high mid 45  < 77 4 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high = mid-1=5 mid 6 high low 5 8 #2
Sequence of Unsuccessful Search - 3 search( 45 ) low high mid 44 <  45   4 6 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 high low 5 5 #3 mid 5 low = mid+1 = 6
Sequence of Unsuccessful Search - 4 search( 45 ) low high mid 4 6 5 Unsuccessful Search low > high 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 5 5 #3 high low 6 5 #4 no more elements to search
Binary Search Routine public   int  binarySearch  ( int []  number,  int  searchValue ) { int   low  = 0,  high  = number.length - 1,  mid = (low + high) / 2; while   ( low <= high && number[mid] != searchValue ) { if   ( number [ mid ]  < searchValue ) { low = mid + 1; }   else   {   //number[mid] > searchValue high = mid - 1; } mid  =  ( low + high )  / 2;  //integer division will truncate } if   ( low > high ) { mid = NOT_FOUND;  } return  mid; }
Binary Search Performance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Comparing N and log 2 N Performance Array Size Linear – N  Binary – log 2 N
Sorting ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Selection Sort ,[object Object],[object Object],[object Object],This is the result of one  pass . 0 1 2 3 4 5 6 7 8 23 17 5 90 12 44 38 84 77 min first exchange 0 1 2 3 4 5 6 7 8 5 17 23 90 12 44 38 84 77 sorted unsorted
Selection Sort Passes 2 3 7 8 Result AFTER one pass is completed. 0 1 2 3 4 5 6 7 8 5 17 23 90 12 44 38 84 77 sorted 5 12 23 90 17 44 38 84 77 5 12 17 90 23 44 38 84 77 5 12 17 23 38 44 77 84 90 5 12 17 23 38 44 77 84 90 1 Pass #
Selection Sort Routine public   void  selectionSort ( int []  number ) { int  startIndex, minIndex, length, temp; length = number.length; for   ( startIndex = 0; startIndex <= length-2; startIndex++ ){ //each iteration of the for loop is one pass minIndex = startIndex; //find the smallest in this pass at position minIndex for   ( int  i = startIndex+1; i <= length-1; i++ ) {   if  (number [ i ]  < number [ minIndex ])  minIndex = i; } //exchange number[startIndex] and number[minIndex] temp   = number [ startIndex ] ; number [ startIndex ]  = number [ minIndex ] ; number [ minIndex ]     = temp; } }
Selection Sort Performance ,[object Object],[object Object],[object Object]
Bubble Sort ,[object Object],[object Object],[object Object],[object Object]
One Pass of Bubble Sort The largest value 90 is at the end of the list. ok 0 1 2 3 4 5 6 7 8 23 17 5 90 12 44 38 84 77 17 23 5 90 12 44 38 84 77 17 5 23 90 12 44 38 84 77 17 5 23 12 90 44 38 84 77 17 5 23 12 44 90 38 84 77 17 5 23 12 44 38 90 84 77 17 5 23 12 44 38 84 90 77 17 5 23 12 44 38 84 77 90 exchange exchange exchange exchange exchange exchange exchange
Bubble Sort Routine public   void  bubbleSort ( int []  number ) { int     temp, bottom, i;  boolean   exchanged = true; bottom = number.length - 2; while   ( exchanged )  { exchanged =  false ;  for   ( i = 0; i <= bottom; i++ ) { if (number [ i ]  > number [ i+1 ])   { temp   = number [ i ] ;  //exchange number [ i ]   = number [ i+1 ] ; number [ i+1 ]  = temp; exchanged =  true ;  //exchange is made   } } bottom--; } }
Bubble Sort Performance ,[object Object],[object Object],[object Object]
Heapsort ,[object Object],[object Object],[object Object],[object Object]
Sample Heap 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 root index left child  of  44 right child  of  44 Level # 1 2 3 4
Heap Constraints ,[object Object],[object Object],[object Object]
Structural Constraints ,[object Object],Nonheaps Heaps
Value Relationship Constraints ,[object Object],Nonheaps Heaps 45 25 16 3 12 22 45 12 34 11 22 9 90 35 24 13 16 12 45 55 16 3 12 58 45 25 33 34 23 22 45 25 55 3 12 22
Heapsort Algorithm ,[object Object],[object Object],[object Object],[object Object]
Extraction Phase ,[object Object],90 23 > max{84, 44}? NO, so swap. 23 > max{77, 12}? NO, so swap. 23 > max{17}? YES, so stop. Before After 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 90 23 84 44 12 5 38 77 17 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 90 84 23 44 12 5 38 77 17 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 90 84 77 44 12 5 38 23 17 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 90 84 77 44 12 5 38 23 17 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 90 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8
Rebuild Steps ,[object Object],90 84 77 44 38 23 17 12 5 Sorting was completed after 8 rebuild steps. 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 Before 90 84 77 44 12 5 38 23 17 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 90 84 77 23 44 12 5 38 17 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 8 90 84 77 44 23 38 12 5 17 0 1 2 3 4 5 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 5 12 17 0 1 2 3 4 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 5 12 0 1 2 3 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 5 0 1 2 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 5 0 1 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 5 0 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 5 0 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 5 Done
Construction Phase ,[object Object],Before 23 17 5 12 44 38 90 84 77 0 1 2 3 4 5 6 7 8 23 17 5 12 44 38 90 84 77 0 1 2 3 4 5 6 7 8 3  (9-2)/2    = 3 23 17 5 12 44 38 90 84 77 0 1 2 3 4 5 6 7 8 2 23 17 44 12 5 38 90 84 77 0 1 2 3 4 5 6 7 8 1 23 90 44 12 5 38 84 17 77 0 1 2 3 4 5 6 7 8 0 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 Done
Heap Implementation ,[object Object],90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 Abstract Heap Structure Concrete Implementation 0 1 2 3 4 5 6 7 8 23 17 38 5 12 77 44 84 90
The construct Method private   void  construct ( ) { for   ( int  i =  ( heap.length-2 )  / 2; i >= 0; i-- ) {  current = i;  done  =  false ;  while   (  !done  ) {   if   (   current has no children   ) { done = true; }   else   { if   ( current node < larger child ) { swap the two nodes ; set current points to the larger child ; }   else   {   done =  true ; } } } } }
The extract Method private void  extract ( ) { for  ( int  size = heap.length-1; size >= 0; size-- ) { remove the root node data ;   move the last node to the root; done  =  false ;  //rebuild the heap with one less element while   ( !done ) { if   ( current has no children ) { done =  true ; }   else   { if   ( current node < larger child ) { swap the two nodes ; set current points to the larger child ; }   else   {   done =  true ; } } }  } }
Heapsort Performance ,[object Object],[object Object],Therefore,  total # nodes in a heap with depth K this holds because of the structural constraint
Heapsort Performance (cont'd) ,[object Object],[object Object],[object Object],Therefore, the total number of comparisons for both phases is
Problem Statement ,[object Object],[object Object]
Overall Plan ,[object Object],[object Object],[object Object]
The AddressBook Interface interface   AddressBook  { public void   add ( Person newPerson ) ; public boolean   delete ( String searchName ) ; public   Person search ( String searchName ) ; public   Person [ ]  sort  ( int   attribute ) ; }
AddressBookVer1 Design ,[object Object],[object Object],[object Object]
Comparing Person Objects ,[object Object],[object Object],[object Object],[object Object]
Modify the Person Class ,[object Object],class  Person  { … public static final int  NAME = 0; public static final int  AGE  = 1; public static int  compareAttribute = NAME;  … public static void  setCompareAttribute ( int  attribute ) { compareAttribute = attribute; } … }
The compareTo Method ,[object Object],Person.setCompareAttribute (Person.NAME); int  compResult = p1.compareTo ( p2 ) ; if   ( compResult < 0 ) { //p1 “less than” p2 }   else if   ( compResult == 0 )   { //p1 “equals” pw }   else   { //p2 “greater than” p2 } public   int  compareTo ( Person p )   { int  compResult; if   (  comparisonAttribute == AGE  ) { int  p2age = p.getAge(); if   (   this .age < p2age  ) { compResult = LESS; } … }   else   {   //compare Name String p2Name = p.getName () ; compResult =  this .name.   compareTo ( p2Name ) ; } return  compResult; }
The sort Method public  Person [ ]  sort  ( int  attribute ) { Person [ ]  sortedList =  new  Person [ count ] ; Person p1, p2, temp; //copy references to sortedList   for   ( int  i = 0; i < count; i++ ) { sortedList [ i ]  = entry [ i ] ; } //Set the comparison attribute Person.setCompareAttribute ( attribute ) ;  //begin the bubble sort on sortedList … } return  sortedList; }
The Use of sortedList in the sort Method
AddressBookVer1 Code Directory:   Chapter11/ Source Files:  AddressBookVer1.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
AddressBookVer2 Design ,[object Object],[object Object],[object Object]
The AgeComparator Class ,[object Object],class   AgeComparator  implements   Comparator  { private final int   LESS = -1; private final int   EQUAL = 0; private final int   MORE = 1; public int   compare ( Object p1, Object p2 ) { int   comparisonResult; int   p1age =  (( Person ) p1 ) .getAge ( ) ; int   p2age =  (( Person ) p2 ) .getAge ( ) ; if   ( p1age < p2age ) { comparisonResult = LESS; }  else if   ( p1age == p2age ) { comparisonResult = EQUAL;   }   else   { assert   p1age > p2age; comparisonResult = MORE; } return   comparisonResult; } }
The NameComparator Class ,[object Object],[object Object],class   NameComparator  implements   Comparator  { public int   compare ( Object p1, Object p2 ) { String p1name =  (( Person ) p1 ) .getName ( ) ; String p2name =  (( Person ) p2 ) .getName ( ) ; return   p1name.compareTo ( p2name ) ; } }
The sort Method ,[object Object],public   Person [ ]  sort  (  int   attribute  ) { if   ( ! ( attribute == Person.NAME ||  attribute == Person.AGE ) ) { throw   new   IllegalArgumentException ( ) ; } Person [ ]  sortedList =  new   Person [  count  ] ; //copy references to sortedList for   ( int   i = 0; i < count; i++ ) { sortedList [ i ]  = entry [ i ] ; } Arrays.sort ( sortedList, getComparator ( attribute )) ; return   sortedList; }
AddressBookVer2 Code Directory:   Chapter11/ Source Files:  AddressBookVer2.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
AddressBookVer3 Design ,[object Object],[object Object],[object Object],[object Object]
The sort Method ,[object Object],public   Person [ ]  sort  (  int   attribute  ) { if  ( ! ( attribute == Person.NAME ||   attribute == Person.AGE ) ) { throw   new   IllegalArgumentException ( ) ; } Person [ ]  sortedList =  new   Person [ entry.size ()] ; entry.values () .toArray ( sortedList ) ; Arrays.sort ( sortedList, getComparator ( attribute )) ; return   sortedList; }
AddressBookVer3 Code Directory:   Chapter11/ Source Files:  AddressBookVer3.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.

Contenu connexe

Tendances

Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure Janki Shah
 
Hash table
Hash tableHash table
Hash tableVu Tran
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIMohamed Loey
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stacksahil kumar
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of AlgorithmsArvind Krishnaa
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4sumitbardhan
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureBalwant Gorad
 
Insertion sort
Insertion sortInsertion sort
Insertion sortMYER301
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm03446940736
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
Algorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structureAlgorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structureVrushali Dhanokar
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 

Tendances (20)

Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Hash table
Hash tableHash table
Hash table
 
Queue
QueueQueue
Queue
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 
Sorting
SortingSorting
Sorting
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms II
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stack
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Quick sort
Quick sortQuick sort
Quick sort
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Algorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structureAlgorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structure
 
Stack
StackStack
Stack
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 

En vedette

Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary SearchReem Alattas
 
Sorting algorithms v01
Sorting algorithms v01Sorting algorithms v01
Sorting algorithms v01Dusan Vuckovic
 
Insertion sort
Insertion sortInsertion sort
Insertion sortalmaqboli
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Muhammad Hammad Waseem
 

En vedette (6)

Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
Sorting algorithms v01
Sorting algorithms v01Sorting algorithms v01
Sorting algorithms v01
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 

Similaire à Sort and Search Algorithms Explained

Similaire à Sort and Search Algorithms Explained (20)

(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Selection sort
Selection sortSelection sort
Selection sort
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 

Plus de Eduardo Bergavera

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyEduardo Bergavera
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentEduardo Bergavera
 

Plus de Eduardo Bergavera (10)

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian Family
 
What is Python?
What is Python?What is Python?
What is Python?
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
 

Dernier

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 

Dernier (20)

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 

Sort and Search Algorithms Explained

  • 1. Chapter 11 Sorting and Searching
  • 2.
  • 3.
  • 4. Search Result number Unsuccessful Search: Successful Search: 23 17 5 90 12 44 38 0 1 2 3 4 5 6 7 8 84 77 NOT_FOUND search( 45 ) search( 12 ) 4
  • 5.
  • 6.
  • 7.
  • 8. Sequence of Successful Search - 1 search( 44 ) low high mid 38 < 44 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high low low = mid+1 = 5 mid 4
  • 9. Sequence of Successful Search - 2 search( 44 ) low high mid 44 < 77 4 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high = mid-1=5 mid 6 high low 5 8 #2
  • 10. Sequence of Successful Search - 3 search( 44 ) low high mid 44 == 44 4 6 Successful Search!! 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 high low 5 5 #3 mid 5
  • 11. Sequence of Unsuccessful Search - 1 search( 45 ) low high mid 38 < 45 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high low low = mid+1 = 5 mid 4
  • 12. Sequence of Unsuccessful Search - 2 search( 45 ) low high mid 45 < 77 4 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 high = mid-1=5 mid 6 high low 5 8 #2
  • 13. Sequence of Unsuccessful Search - 3 search( 45 ) low high mid 44 < 45 4 6 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 high low 5 5 #3 mid 5 low = mid+1 = 6
  • 14. Sequence of Unsuccessful Search - 4 search( 45 ) low high mid 4 6 5 Unsuccessful Search low > high 5 12 17 23 38 44 77 0 1 2 3 4 5 6 7 8 84 90 0 8 #1 5 8 #2 5 5 #3 high low 6 5 #4 no more elements to search
  • 15. Binary Search Routine public int binarySearch ( int [] number, int searchValue ) { int low = 0, high = number.length - 1, mid = (low + high) / 2; while ( low <= high && number[mid] != searchValue ) { if ( number [ mid ] < searchValue ) { low = mid + 1; } else { //number[mid] > searchValue high = mid - 1; } mid = ( low + high ) / 2; //integer division will truncate } if ( low > high ) { mid = NOT_FOUND; } return mid; }
  • 16.
  • 17. Comparing N and log 2 N Performance Array Size Linear – N Binary – log 2 N
  • 18.
  • 19.
  • 20. Selection Sort Passes 2 3 7 8 Result AFTER one pass is completed. 0 1 2 3 4 5 6 7 8 5 17 23 90 12 44 38 84 77 sorted 5 12 23 90 17 44 38 84 77 5 12 17 90 23 44 38 84 77 5 12 17 23 38 44 77 84 90 5 12 17 23 38 44 77 84 90 1 Pass #
  • 21. Selection Sort Routine public void selectionSort ( int [] number ) { int startIndex, minIndex, length, temp; length = number.length; for ( startIndex = 0; startIndex <= length-2; startIndex++ ){ //each iteration of the for loop is one pass minIndex = startIndex; //find the smallest in this pass at position minIndex for ( int i = startIndex+1; i <= length-1; i++ ) { if (number [ i ] < number [ minIndex ]) minIndex = i; } //exchange number[startIndex] and number[minIndex] temp = number [ startIndex ] ; number [ startIndex ] = number [ minIndex ] ; number [ minIndex ] = temp; } }
  • 22.
  • 23.
  • 24. One Pass of Bubble Sort The largest value 90 is at the end of the list. ok 0 1 2 3 4 5 6 7 8 23 17 5 90 12 44 38 84 77 17 23 5 90 12 44 38 84 77 17 5 23 90 12 44 38 84 77 17 5 23 12 90 44 38 84 77 17 5 23 12 44 90 38 84 77 17 5 23 12 44 38 90 84 77 17 5 23 12 44 38 84 90 77 17 5 23 12 44 38 84 77 90 exchange exchange exchange exchange exchange exchange exchange
  • 25. Bubble Sort Routine public void bubbleSort ( int [] number ) { int temp, bottom, i; boolean exchanged = true; bottom = number.length - 2; while ( exchanged ) { exchanged = false ; for ( i = 0; i <= bottom; i++ ) { if (number [ i ] > number [ i+1 ]) { temp = number [ i ] ; //exchange number [ i ] = number [ i+1 ] ; number [ i+1 ] = temp; exchanged = true ; //exchange is made } } bottom--; } }
  • 26.
  • 27.
  • 28. Sample Heap 90 84 44 12 5 38 77 17 23 0 1 2 3 4 5 6 7 8 root index left child of 44 right child of 44 Level # 1 2 3 4
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. The construct Method private void construct ( ) { for ( int i = ( heap.length-2 ) / 2; i >= 0; i-- ) { current = i; done = false ; while ( !done ) { if ( current has no children ) { done = true; } else { if ( current node < larger child ) { swap the two nodes ; set current points to the larger child ; } else { done = true ; } } } } }
  • 38. The extract Method private void extract ( ) { for ( int size = heap.length-1; size >= 0; size-- ) { remove the root node data ; move the last node to the root; done = false ; //rebuild the heap with one less element while ( !done ) { if ( current has no children ) { done = true ; } else { if ( current node < larger child ) { swap the two nodes ; set current points to the larger child ; } else { done = true ; } } } } }
  • 39.
  • 40.
  • 41.
  • 42.
  • 43. The AddressBook Interface interface AddressBook { public void add ( Person newPerson ) ; public boolean delete ( String searchName ) ; public Person search ( String searchName ) ; public Person [ ] sort ( int attribute ) ; }
  • 44.
  • 45.
  • 46.
  • 47.
  • 48. The sort Method public Person [ ] sort ( int attribute ) { Person [ ] sortedList = new Person [ count ] ; Person p1, p2, temp; //copy references to sortedList for ( int i = 0; i < count; i++ ) { sortedList [ i ] = entry [ i ] ; } //Set the comparison attribute Person.setCompareAttribute ( attribute ) ; //begin the bubble sort on sortedList … } return sortedList; }
  • 49. The Use of sortedList in the sort Method
  • 50. AddressBookVer1 Code Directory: Chapter11/ Source Files: AddressBookVer1.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. AddressBookVer2 Code Directory: Chapter11/ Source Files: AddressBookVer2.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
  • 56.
  • 57.
  • 58. AddressBookVer3 Code Directory: Chapter11/ Source Files: AddressBookVer3.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.

Notes de l'éditeur

  1. Note: In the case of unsuccessful search, all elements in the array are compared against the search value, so the total number of comparisons is N. However, the actual number of times the while loop is executed is N+1 because we need one more go around to determine that loc becomes equal to number.length .
  2. Note: The value of log 2 N is a real number. Since the number of comparisons done is an integer, the result of log 2 N is rounded up to an integer in the third column.
  3. The figure shows the whole eight passes. The illustration for each pass shows the state right BEFORE the exchange was made for that pass. The illustrations in the slide show the state AFTER the exchange was made for that pass.
  4. What is the meaning behind the name “bubble” sort? Notice the effect of one pass is to migrate the largest element to the last position of the array. In addition, because we are exchanging the pairs if they are out of order, other elements migrate toward the end of the array. If we view the array vertically with the first position at the bottom and the last position at the top, the data movements we see is like bubbles moving toward the surface of water.
  5. The bubble sort routine is implemented by exploiting the following two properties: 1. After one pass through the array, the largest element will be at the end of the array. 2. During one pass, if no pair of consecutive entries is out of order, then the array is sorted.
  6. The selection sort will carry out N-1 passes no matter what. Whether the array is already sorted or very close to being sorted does not matter to the selection sort. It will carry out the same number of comparisons in sorting a given array. The bubble sort, on the other hand, can detect if the array is or has become sorted during the sorting process. So the bubble sort is adaptable, it does fewer comparisons for the arrays that are closer to being sorted than those that are not. In addition to the larger number of data movements during a single pass, the capability of checking the “sortedness” of the array enables the bubble sort routine to complete the whole sorting process much quicker than the selection sort. Indeed, the only situation that causes the bubble sort routine to execute the worst case number of comparisons is when the original array is in the reverse order (i.e., in descending order).
  7. We use integers as data values for the examples in this section. The topmost node is called the root of a heap. Nodes in a heap are indexed 0, 1, 2, and so forth in the top-to-bottom, left-to-right order starting from the root. A node in a heap has either zero, one, or two children. The children of a node are distinguished as the node’s left and right children. If a node has only one child, then it is the left child of the node.
  8. The heap structure can be characterized as an abstract data structure because the Java language (and others) does not include such data structure as a part of its language definition. An array is a concrete data structure that is a part of the Java language and the one which we can use effectively here to implement the abstract data structure heap. This slide shows the correspondence between the heap and the array representation. An important aspect in deciding which data structure to use is the ease of locating a given node’s left and right child. With an array implementation, we can locate any node’s left and right child easily. A node with index I has its left child at index 2ÞI + 1 and right child at index 2ÞI + 2.
  9. private void construct( ) { int current, maxChildIndex; boolean done; for (int i = (heap.length-2) / 2; i &gt;= 0; i--) { current = i; done = false; while ( !done ) {//perform one rebuild step //with the node at index i if ( 2*current+1 &gt; heap.length-1 ) { //current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, heap.length-1 ); if ( heap[current] &lt; heap[maxChildIndex] ) { //a child is larger, so swap and continue swap( current, maxChildIndex ); current = maxChildIndex; } else { //the value relationship constraint //is satisfied, so stop done = true; } } } } testPrint( heap.length ); //TEMP }
  10. private void extract( ) { int current, maxChildIndex; boolean done; for (int size = heap.length-1; size &gt;= 0; size--) { //remove the root node data sortedList[size] = heap[ 0 ]; //move the last node to the root heap[ 0 ] = heap[size]; //rebuild the heap with one less element current = 0; done = false; while ( !done ) { if ( 2*current+1 &gt; size ) {//current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, size ); if ( heap[current] &lt; heap[maxChildIndex] ) { //a child is larger, so swap and continue swap( current, maxChildIndex ); current = maxChildIndex; } else { //value relationship constraint //is satisfied, so stop done = true; } } } testPrint( size ); //TEMP } }
  11. public int compareTo( Person person ) { int comparisonResult; if ( compareAttribute == AGE ) { int p2age = person.getAge( ); if (this.age &lt; p2age) { comparisonResult = LESS; } else if (this.age == p2age) { comparisonResult = EQUAL; } else { //this.age &gt; p2age comparisonResult = MORE; } } else { //compare names with String’s compareTo String p2name = person.getName( ); comparisonResult = this.name.compareTo( p2name ); } return comparisonResult; }
  12. public Person[ ] sort ( int attribute ) { Person[ ] sortedList = new Person[ count ]; Person p1, p2, temp; //copy references to sortedList; see Figure 10.17 for (int i = 0; i &lt; count; i++) { sortedList[i] = entry[i]; } //Set the comparison attribute Person.setCompareAttribute( attribute ); //begin the bubble sort on sortedList int bottom, i, comparisonResult; boolean exchanged = true; bottom = sortedList.length - 2; while ( exchanged ) { exchanged = false; for (i = 0; i &lt;= bottom; i++) { p1 = sortedList[i]; p2 = sortedList[i+1]; comparisonResult = p1.compareTo(p2, attribute); if ( comparisonResult &gt; 0 ) { //p1 is &apos;larger&apos; sortedList[i] = p2; //than p2,so sortedList[i+1] = p1; //exchange exchanged = true; //exchange is made } } bottom--; } return sortedList; }
  13. Please use your Java IDE to view the source files and run the program.
  14. Please use your Java IDE to view the source files and run the program.
  15. Please use your Java IDE to view the source files and run the program.