SlideShare a Scribd company logo
Chapter 8.6 Searching and Sorting Arrays
Sequential Search A  Sequential Search  can be used to determine if a specific value (the  search key ) is in an array. Approach is to start with the first element and compare each element  to the search key: If found, return the index of the element that contains the search key. If not found, return  -1. Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array.
Code to Perform a Sequential Search public int findWinners( int key ) { for ( int i = 0; i < winners.length; i++ ) { if ( winners[i] == key )   return i; }  return -1; } See Examples 8.14 and 8.15
Searching a Sorted Array When an array's elements are in random order, our Sequential Search   method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search   becomes. We could simplify the search by arranging the elements in numeric order, which is called  sorting the array .  Once the array is sorted, we can use various search algorithms to speed up a search.
Sequential Search of a Sorted Array When the array is sorted, we can implement a more efficient algorithm for a sequential search. If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key. All elements past that position will be greater than the value of that element, and therefore, greater than the search key.
Sample Code public int searchSortedArray( int key ) { for ( int i = 0; i < array.length &&   array[i] <= key ; i++ ) { if ( array[i] == key )   return i; }     return –1; // end of array reached without // finding key   or   // an element larger than  // the key was found }
Binary Search A  Binary Search  is like the &quot;Guess a Number&quot; game.  To guess a number between 1 and 100, we start with 50 (halfway between the beginning number and the end number).  If we learn that the number is greater than 50, we immediately know the number is not 1 - 49.  If we learn that the number is less than 50, we immediately know the number is not 51 - 100.  We keep guessing the number that is in the middle of the remaining numbers (eliminating half the remaining numbers) until we find the number.
Binary Search The &quot;Guess a Number&quot; approach works because  1 - 100 are a &quot;sorted&quot; set of numbers. To use a Binary Search, the array must be sorted. Our Binary Search will attempt to find a search key in a sorted array. If the search key is found, we return the index of the element with that value. If the search key is not found,we return -1.
The Binary Search Algorithm We begin by  comparing the middle element of the array and the search key.  If they are equal, we found the search key and return the index of the middle element. If the middle element's value is greater than the search key, then the search key cannot be found in elements with higher array indexes. So, we continue our search in the left half of the array.  If the middle element's value is less than the search key, then the search key cannot be found in elements with lower array indexes. So, we continue our search in the right half of the array.
The Binary Search Algorithm (con't) As we keep searching, the subarray we search keeps shrinking in size. In fact, the size of the subarray we search is cut in half at every iteration.   If the search key is not in the array, the subarray we search will eventually become empty. At that point, we know that we will not find our search key in the array, and we return –1.  
Example of a Binary Search For example, we will search for the value 7 in this sorted array: To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value 45.
Binary Search Example (con't) Because 7 is less than 45, we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 7 to the value 8.
Binary Search Example (con't) Because 7 is less than 8, we eliminate all array elements higher than our current middle element (3) and make elements 0 through 2 the new subarray to search. The index of the center element is now 1, so we compare 7 to the value 6.
Binary Search: Finding the search key Because 7 is greater than 6, we eliminate array elements lower than our current middle element (1) and make element 2 the new subarray to search. The value of element 2 matches the search key, so our search is successful and we return the index 2.
Binary Search Example 2 This time, we search for a value not found in the array, 34. Again, we start with the entire array and find the index of the middle element, which is 8.  We compare our search key (34) with the value 45.
Binary Search Example 2 (con't) Because 34 is less than 45, we eliminate array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 34 to the value 8.
Binary Search Example 2 (con't) Because 34 is greater than 8, we eliminate array elements lower than our current middle element and consider elements 4 through 7 the new subarray to search. The index of the center element is now 5, so we compare 34 to the value 15.
Binary Search Example 2 (con't) Again, we eliminate array elements lower than our current middle element and make elements 6 and 7 the new subarray to search. The index of the center element is now 6, so we compare 34 to the value 22.
Binary Search 2: search key is not found Next, we eliminate array elements lower than our current middle element and make element 7 the new subarray to search. We compare 34 to the value 36, and attempt to eliminate the higher subarray, which leaves an empty subarray. We have determined that 32 is not in the array. We return -1 to indicate an unsuccessful search.
Binary Search Code public int binarySearch( int [] array, int key ) { int start = 0, end = array.length - 1; while ( end >= start ) { int middle = ( start + end ) / 2;  if ( array[middle] == key ) return middle;  // key found  else if ( array[middle] > key ) end = middle - 1; // search left  else start = middle + 1; // search right  } return -1;  // key not found }
Sorting an Array Selection Sort Bubble Sort Sorting Array objects
Selection Sort In a  Selection Sort , we select the largest element in the array and place it at the end of the array. Then we select the next-largest element and put it in the next-to-last position in the array, and so on.  To do this, we consider the unsorted portion of the array as a  subarray .  We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. We continue until the subarray has only one element. At that time, the array is sorted.
The Selection Sort Algorithm To sort an array with  n  elements in ascending order: 1.  Consider the  n  elements as a subarray with  m = n  elements. 2.  Find the index of the largest value in this subarray. 3.  Swap the values of the element with the largest value and the element in the last position in the subarray. 4.  Consider a new subarray of  m = m - 1  elements by eliminating the last element in the previous subarray 5.  Repeat steps 2 through 4 until  m = 1 .
Selection Sort Example In the beginning, the entire array is the unsorted subarray: We swap the largest element with the last element:
Selection Sort Example (continued) Again, we swap the largest and last elements: When there is only 1 unsorted element, the array is completely sorted:
Swapping Values To swap two values, we define a temporary variable to hold the value of one of the elements, so that we don't lose that value during the swap.  To swap elements  a  and  b : define a temporary variable,  temp. assign element  a  to  temp. assign element  b  to element  a. assign  temp  to element  b.
Swapping Example This code will swap elements 3 and 6 in an  int  array named  array : int temp;    // step 1 temp = array[3];   // step 2 array[3] = array[6];  // step 3 array[6] = temp;  // step 4  See Examples 8.16 & 8.17
Bubble Sort The basic approach to a Bubble Sort is to make multiple passes through the array.  In each pass, we compare adjacent elements. If any two  adjacent  elements are out of order, we put them in order by swapping their values.  At the end of each pass, one more element has &quot;bubbled&quot; up to its correct position . We keep making passes through the array until all the elements are in order.
Bubble Sort Algorithm To sort an array of  n  elements in ascending order, we use a nested loop: The outer loop executes  n – 1  times.   For each iteration of the outer loop, the inner loop steps through all the unsorted elements of the array and does the following: Compares the current element with the next element in the array. If the next element is smaller, it swaps the two elements.
Bubble Sort  Pseudocode for i = 0 to last array index – 1 by 1 { for j = 0 to ( last array index – i - 1 ) by 1 { if ( 2 consecutive elements are not in order )   swap the elements } }
Bubble Sort Example At the beginning, the array is: We compare elements 0 (17) and 1 (26) and find they are in the correct order, so we do not swap.
Bubble Sort Example (con't) The inner loop counter is incremented to the next element: We compare elements 1 (26) and 2 (5), and find they are not in the correct order, so we swap them.
Bubble Sort Example (con't) The inner loop counter is incremented to the next element: We compare elements 2 (26) and 3 (2), and find they are not in the correct order, so we swap them. The inner loop completes, which ends our first pass through the array.
Bubble Sort Example (2 nd  pass) The largest value in the array (26) has bubbled up to its correct position. We begin the second pass through the array. We compare elements 0 (17) and 1 (5) and swap them.
Bubble Sort Example (2 nd  pass) We compare elements 1 (17) and 2 (2) and swap. This ends the second pass through the array. The second-largest element (17) has bubbled up to its correct position.
Bubble Sort (3 rd  pass) We begin the last pass through the array. We compare element 0 (5) with element 1 (2) and swap them.
Bubble Sort ( complete ) The third-largest value (5) has bubbled up to its correct position. Only one element remains, so the array is now sorted.
Bubble Sort Code for ( int i = 0; i < array.length - 1; i++ )  {   for ( int j = 0; j < array.length – i - 1; j++ )   {   if ( array[j] > array[j + 1] )   {   // swap the elements   int temp = array[j + 1];   array[j + 1] = array[j];   array[j] = temp; }   } // end inner for loop   } // end outer for loop See Examples 8.18 & 8.19
Sorting Arrays of Objects In arrays of objects, the array elements are object references.  Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a  sort key . For example, in an email object, the sort key might be the date received.
Example Code to sort an array of  Auto  objects using  model  as the sort key: for ( int i = 0; i < array.length - 1; i++ )  {   for ( int j = 0; j < array.length - i - 1; j++ ) { if ( array[j].getModel( ).compareTo(  array[j + 1].getModel( ) ) > 0 ) {   Auto  temp = array[j + 1];   array[j + 1] = array[j];   array[j] = temp; } end if statement } // end inner for loop } // end outer for loop

More Related Content

PPTX
Searching & Sorting Algorithms
Rahul Jamwal
 
PPTX
Sorting
Jasmine Chen
 
PPT
Sorting
Abhishek Khune
 
PPTX
Sorting and searching arrays binary search algorithm
David Burks-Courses
 
PPT
(Data Structure) Chapter11 searching & sorting
Fadhil Ismail
 
PPT
SEARCHING AND SORTING ALGORITHMS
Gokul Hari
 
PDF
Binary Search - Design & Analysis of Algorithms
Drishti Bhalla
 
PPTX
Algorithm & data structures lec4&5
Abdul Khan
 
Searching & Sorting Algorithms
Rahul Jamwal
 
Sorting
Jasmine Chen
 
Sorting and searching arrays binary search algorithm
David Burks-Courses
 
(Data Structure) Chapter11 searching & sorting
Fadhil Ismail
 
SEARCHING AND SORTING ALGORITHMS
Gokul Hari
 
Binary Search - Design & Analysis of Algorithms
Drishti Bhalla
 
Algorithm & data structures lec4&5
Abdul Khan
 

What's hot (20)

PDF
Chapter 14 Searching and Sorting
MuhammadBakri13
 
PPT
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
PPT
L10 sorting-searching
mondalakash2012
 
PPTX
Searching linear &amp; binary search
nikunjandy
 
PPTX
7 searching injava-binary
irdginfo
 
PPTX
Coin Changing, Binary Search , Linear Search - Algorithm
Md Sadequl Islam
 
PPTX
data structures and algorithms Unit 3
infanciaj
 
PDF
Searching/Sorting algorithms
Huy Nguyen
 
PDF
Binary search algorithm
maamir farooq
 
PPTX
Binary search
Raghu nath
 
PPTX
Rahat &amp; juhith
Rj Juhith
 
DOC
Selection sort
asra khan
 
PPSX
Linear and binary search
Arjunsinh Jadeja
 
PPTX
Binary search
AparnaKumari31
 
PPT
Introduction to Data Structures Sorting and searching
Mvenkatarao
 
PDF
Sorting Algorithms
Mohammed Hussein
 
PDF
Data structures arrays
maamir farooq
 
PPT
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Tiểu Hổ
 
PPT
Data Structures- Part3 arrays and searching algorithms
Abdullah Al-hazmy
 
PPTX
Insertion Sorting
FarihaHabib123
 
Chapter 14 Searching and Sorting
MuhammadBakri13
 
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
L10 sorting-searching
mondalakash2012
 
Searching linear &amp; binary search
nikunjandy
 
7 searching injava-binary
irdginfo
 
Coin Changing, Binary Search , Linear Search - Algorithm
Md Sadequl Islam
 
data structures and algorithms Unit 3
infanciaj
 
Searching/Sorting algorithms
Huy Nguyen
 
Binary search algorithm
maamir farooq
 
Binary search
Raghu nath
 
Rahat &amp; juhith
Rj Juhith
 
Selection sort
asra khan
 
Linear and binary search
Arjunsinh Jadeja
 
Binary search
AparnaKumari31
 
Introduction to Data Structures Sorting and searching
Mvenkatarao
 
Sorting Algorithms
Mohammed Hussein
 
Data structures arrays
maamir farooq
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Tiểu Hổ
 
Data Structures- Part3 arrays and searching algorithms
Abdullah Al-hazmy
 
Insertion Sorting
FarihaHabib123
 
Ad

Similar to Searching Sorting (20)

DOCX
MODULE 5-Searching and-sorting
nikshaikh786
 
PPT
1 D Arrays in C++
poonam.rwalia
 
PDF
advanced searching and sorting.pdf
haramaya university
 
PPTX
Dsa – data structure and algorithms searching
sajinis3
 
PPTX
Chapter 3 - Data Structure and Algorithms.pptx
tarrebulehora
 
PPTX
Searching and Sorting Algorithms in Data Structures
poongothai11
 
PPTX
Searching and sorting
PoojithaBollikonda
 
PPTX
Data Structures_ Sorting & Searching
ThenmozhiK5
 
PPTX
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
PPTX
Lecture_Oct26.pptx
SylrizcinMarieManzo3
 
PDF
Unit v data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
PPTX
Searching techniques
ER Punit Jain
 
PPTX
Searching techniques
Archana Burujwale
 
PPTX
Analysis of Algorithm - Binary Search.pptx
Maulana Abul Kalam Azad University of Technology
 
PPT
Ch05 Black Jack
leminhvuong
 
PDF
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
Sowmya Jyothi
 
PDF
Searching
A. S. M. Shafi
 
PDF
searching
A. S. M. Shafi
 
PPTX
Data structure Unit - II Searching and Sorting.pptx
gavanisanjana
 
MODULE 5-Searching and-sorting
nikshaikh786
 
1 D Arrays in C++
poonam.rwalia
 
advanced searching and sorting.pdf
haramaya university
 
Dsa – data structure and algorithms searching
sajinis3
 
Chapter 3 - Data Structure and Algorithms.pptx
tarrebulehora
 
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Searching and sorting
PoojithaBollikonda
 
Data Structures_ Sorting & Searching
ThenmozhiK5
 
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
Lecture_Oct26.pptx
SylrizcinMarieManzo3
 
Unit v data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Searching techniques
ER Punit Jain
 
Searching techniques
Archana Burujwale
 
Analysis of Algorithm - Binary Search.pptx
Maulana Abul Kalam Azad University of Technology
 
Ch05 Black Jack
leminhvuong
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
Sowmya Jyothi
 
Searching
A. S. M. Shafi
 
searching
A. S. M. Shafi
 
Data structure Unit - II Searching and Sorting.pptx
gavanisanjana
 
Ad

Recently uploaded (20)

PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
The Future of Artificial Intelligence (AI)
Mukul
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Doc9.....................................
SofiaCollazos
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 

Searching Sorting

  • 1. Chapter 8.6 Searching and Sorting Arrays
  • 2. Sequential Search A Sequential Search can be used to determine if a specific value (the search key ) is in an array. Approach is to start with the first element and compare each element to the search key: If found, return the index of the element that contains the search key. If not found, return -1. Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array.
  • 3. Code to Perform a Sequential Search public int findWinners( int key ) { for ( int i = 0; i < winners.length; i++ ) { if ( winners[i] == key ) return i; } return -1; } See Examples 8.14 and 8.15
  • 4. Searching a Sorted Array When an array's elements are in random order, our Sequential Search method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search becomes. We could simplify the search by arranging the elements in numeric order, which is called sorting the array . Once the array is sorted, we can use various search algorithms to speed up a search.
  • 5. Sequential Search of a Sorted Array When the array is sorted, we can implement a more efficient algorithm for a sequential search. If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key. All elements past that position will be greater than the value of that element, and therefore, greater than the search key.
  • 6. Sample Code public int searchSortedArray( int key ) { for ( int i = 0; i < array.length && array[i] <= key ; i++ ) { if ( array[i] == key ) return i; }   return –1; // end of array reached without // finding key or // an element larger than // the key was found }
  • 7. Binary Search A Binary Search is like the &quot;Guess a Number&quot; game. To guess a number between 1 and 100, we start with 50 (halfway between the beginning number and the end number). If we learn that the number is greater than 50, we immediately know the number is not 1 - 49. If we learn that the number is less than 50, we immediately know the number is not 51 - 100. We keep guessing the number that is in the middle of the remaining numbers (eliminating half the remaining numbers) until we find the number.
  • 8. Binary Search The &quot;Guess a Number&quot; approach works because 1 - 100 are a &quot;sorted&quot; set of numbers. To use a Binary Search, the array must be sorted. Our Binary Search will attempt to find a search key in a sorted array. If the search key is found, we return the index of the element with that value. If the search key is not found,we return -1.
  • 9. The Binary Search Algorithm We begin by comparing the middle element of the array and the search key. If they are equal, we found the search key and return the index of the middle element. If the middle element's value is greater than the search key, then the search key cannot be found in elements with higher array indexes. So, we continue our search in the left half of the array. If the middle element's value is less than the search key, then the search key cannot be found in elements with lower array indexes. So, we continue our search in the right half of the array.
  • 10. The Binary Search Algorithm (con't) As we keep searching, the subarray we search keeps shrinking in size. In fact, the size of the subarray we search is cut in half at every iteration.   If the search key is not in the array, the subarray we search will eventually become empty. At that point, we know that we will not find our search key in the array, and we return –1.  
  • 11. Example of a Binary Search For example, we will search for the value 7 in this sorted array: To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value 45.
  • 12. Binary Search Example (con't) Because 7 is less than 45, we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 7 to the value 8.
  • 13. Binary Search Example (con't) Because 7 is less than 8, we eliminate all array elements higher than our current middle element (3) and make elements 0 through 2 the new subarray to search. The index of the center element is now 1, so we compare 7 to the value 6.
  • 14. Binary Search: Finding the search key Because 7 is greater than 6, we eliminate array elements lower than our current middle element (1) and make element 2 the new subarray to search. The value of element 2 matches the search key, so our search is successful and we return the index 2.
  • 15. Binary Search Example 2 This time, we search for a value not found in the array, 34. Again, we start with the entire array and find the index of the middle element, which is 8. We compare our search key (34) with the value 45.
  • 16. Binary Search Example 2 (con't) Because 34 is less than 45, we eliminate array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 34 to the value 8.
  • 17. Binary Search Example 2 (con't) Because 34 is greater than 8, we eliminate array elements lower than our current middle element and consider elements 4 through 7 the new subarray to search. The index of the center element is now 5, so we compare 34 to the value 15.
  • 18. Binary Search Example 2 (con't) Again, we eliminate array elements lower than our current middle element and make elements 6 and 7 the new subarray to search. The index of the center element is now 6, so we compare 34 to the value 22.
  • 19. Binary Search 2: search key is not found Next, we eliminate array elements lower than our current middle element and make element 7 the new subarray to search. We compare 34 to the value 36, and attempt to eliminate the higher subarray, which leaves an empty subarray. We have determined that 32 is not in the array. We return -1 to indicate an unsuccessful search.
  • 20. Binary Search Code public int binarySearch( int [] array, int key ) { int start = 0, end = array.length - 1; while ( end >= start ) { int middle = ( start + end ) / 2; if ( array[middle] == key ) return middle; // key found else if ( array[middle] > key ) end = middle - 1; // search left else start = middle + 1; // search right } return -1; // key not found }
  • 21. Sorting an Array Selection Sort Bubble Sort Sorting Array objects
  • 22. Selection Sort In a Selection Sort , we select the largest element in the array and place it at the end of the array. Then we select the next-largest element and put it in the next-to-last position in the array, and so on. To do this, we consider the unsorted portion of the array as a subarray . We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. We continue until the subarray has only one element. At that time, the array is sorted.
  • 23. The Selection Sort Algorithm To sort an array with n elements in ascending order: 1.  Consider the n elements as a subarray with m = n elements. 2.  Find the index of the largest value in this subarray. 3.  Swap the values of the element with the largest value and the element in the last position in the subarray. 4.  Consider a new subarray of m = m - 1 elements by eliminating the last element in the previous subarray 5.  Repeat steps 2 through 4 until m = 1 .
  • 24. Selection Sort Example In the beginning, the entire array is the unsorted subarray: We swap the largest element with the last element:
  • 25. Selection Sort Example (continued) Again, we swap the largest and last elements: When there is only 1 unsorted element, the array is completely sorted:
  • 26. Swapping Values To swap two values, we define a temporary variable to hold the value of one of the elements, so that we don't lose that value during the swap. To swap elements a and b : define a temporary variable, temp. assign element a to temp. assign element b to element a. assign temp to element b.
  • 27. Swapping Example This code will swap elements 3 and 6 in an int array named array : int temp; // step 1 temp = array[3]; // step 2 array[3] = array[6]; // step 3 array[6] = temp; // step 4 See Examples 8.16 & 8.17
  • 28. Bubble Sort The basic approach to a Bubble Sort is to make multiple passes through the array. In each pass, we compare adjacent elements. If any two adjacent elements are out of order, we put them in order by swapping their values. At the end of each pass, one more element has &quot;bubbled&quot; up to its correct position . We keep making passes through the array until all the elements are in order.
  • 29. Bubble Sort Algorithm To sort an array of n elements in ascending order, we use a nested loop: The outer loop executes n – 1 times. For each iteration of the outer loop, the inner loop steps through all the unsorted elements of the array and does the following: Compares the current element with the next element in the array. If the next element is smaller, it swaps the two elements.
  • 30. Bubble Sort Pseudocode for i = 0 to last array index – 1 by 1 { for j = 0 to ( last array index – i - 1 ) by 1 { if ( 2 consecutive elements are not in order ) swap the elements } }
  • 31. Bubble Sort Example At the beginning, the array is: We compare elements 0 (17) and 1 (26) and find they are in the correct order, so we do not swap.
  • 32. Bubble Sort Example (con't) The inner loop counter is incremented to the next element: We compare elements 1 (26) and 2 (5), and find they are not in the correct order, so we swap them.
  • 33. Bubble Sort Example (con't) The inner loop counter is incremented to the next element: We compare elements 2 (26) and 3 (2), and find they are not in the correct order, so we swap them. The inner loop completes, which ends our first pass through the array.
  • 34. Bubble Sort Example (2 nd pass) The largest value in the array (26) has bubbled up to its correct position. We begin the second pass through the array. We compare elements 0 (17) and 1 (5) and swap them.
  • 35. Bubble Sort Example (2 nd pass) We compare elements 1 (17) and 2 (2) and swap. This ends the second pass through the array. The second-largest element (17) has bubbled up to its correct position.
  • 36. Bubble Sort (3 rd pass) We begin the last pass through the array. We compare element 0 (5) with element 1 (2) and swap them.
  • 37. Bubble Sort ( complete ) The third-largest value (5) has bubbled up to its correct position. Only one element remains, so the array is now sorted.
  • 38. Bubble Sort Code for ( int i = 0; i < array.length - 1; i++ ) { for ( int j = 0; j < array.length – i - 1; j++ ) { if ( array[j] > array[j + 1] ) { // swap the elements int temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } // end inner for loop } // end outer for loop See Examples 8.18 & 8.19
  • 39. Sorting Arrays of Objects In arrays of objects, the array elements are object references. Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a sort key . For example, in an email object, the sort key might be the date received.
  • 40. Example Code to sort an array of Auto objects using model as the sort key: for ( int i = 0; i < array.length - 1; i++ ) { for ( int j = 0; j < array.length - i - 1; j++ ) { if ( array[j].getModel( ).compareTo( array[j + 1].getModel( ) ) > 0 ) { Auto temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } end if statement } // end inner for loop } // end outer for loop