Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
201707 CSE110 Lecture 30
1. CSE110
Principles of Programming
with Java
Lecture 30:
Sorting and Searching – Arrays of Objects
Javier Gonzalez-Sanchez
javiergs@asu.edu
javiergs.engineering.asu.edu
Office Hours: By appointment
6. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 6
Arrays of Objects | swap
// int temp = data[index_1];
// data[index_1] = data[index_2];
// data[index_2] = temp;
How to do this for arrays of objects?
JohnMary AliceRobert
4 1 3 2
7. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 7
Swap | Arrays of Objects
What about
Sort (Bubble or Selection)?
Search (Linear or Binary)?
JohnMary AliceRobert
4 1 3 2
8. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 8
What about “Selection Sort” for A of O?
// Do changes in the highlighted places
public static void selectionSort (int[] data) {
int minIndex;
for (int index=0; index<data.length-1; index++) {
minIndex = index;
for (int scan=index+1;scan<data.length; scan++){
if (data[scan] < data[minIndex]) {
minIndex = scan;
}
}
//swap the two elements, data[minIndex] and data[index]
int temp = data[minIndex];
data[minIndex] = data[index];
data[index] = temp;
}
}
9. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 9
What about “Binary Search” for A of O?
// Do changes in the highlighted places
public static int binarySearch (int[] data, int target) {
int start = 0, end = data.length-1, middle;
int position = -1; //return -1 if not found
boolean found = false;
while (found == false && start <= end) {
middle = (start+end)/2;
if (data[middle] == target){
found = true;
position = middle;
} else if (data[middle] > target)
end = middle - 1;
else
start = middle + 1;
}
return position; //return -1 if not found
}
10. CSE110 - Principles of Programming
Javier Gonzalez-Sanchez
javiergs@asu.edu
Summer 2017
Disclaimer. These slides can only be used as study material for the class CSE110 at ASU. They cannot be distributed or used for another purpose.