Presentation is loading. Please wait.

Presentation is loading. Please wait.

Agenda About the homework EvensAndOdds Array class Array Sorting

Similar presentations


Presentation on theme: "Agenda About the homework EvensAndOdds Array class Array Sorting"— Presentation transcript:

1 Agenda About the homework EvensAndOdds Array class Array Sorting
Bubble sort Selection sort practice

2 Remarks on the homework
If you have 2 arrarys, one for even, one for odds, you will find some elements in both arrays have no data and initialized to 0. How to make the program better?

3 Array class Built in class and ready for use Provided in the java.util.Arrays Sort method(function) syntax Arrays.sort(<array name>); BinarySearch syntax Arrays.binarySearch(<arry>, key); => for this to work right, precondition: Array has to be sorted in ascending order

4 Practice int[] bArry = {16, 2, 31, 9}; System.out.println("array before sorting: "); for(int dummy : bArry) System.out.print(dummy+ " "); System.out.println(" "); Arrays.sort(bArry);

5 Bubble Sort 4 2 5 1 3 Original data 4 2 5 1 3 Compare the shaded pair. 4>2, so swap 2 4 5 1 3 Swap completed Compare the shaded pair. No swap needed 2 4 5 1 3 2 4 5 1 3 Compare the shaded pair. 5>1, so swap 2 4 1 5 3 Swap completed. 2 4 1 5 3 Compare the shaded pair. 5>3, so swap 2 4 1 3 5 Swap completed

6 selection Sort 4 2 5 1 3 Original data 1st pass: select smallest value in gray area just above.. It’s 1. Then 1 and 4 have now been swapped. 11 2 5 4 3 2nd pass: select smallest value in gray area just above.. It’s 2. No swap necessary since the 2 above is less than 3. 11 2 5 4 3 3rd pass: select smallest value in gray area just above.. It’s 3. Then 3 and 5 have now been swapped. 11 2 3 4 5 4th pass: select smallest value in gray area just above.. It’s 5. No swap necessary since the 4 is less than 5. 11 2 3 4 5

7 Swap method Original values p = 5; q = 97; Swapped values p = 97; q=5;
How? temp = p; p = q; q = temp; temp 5 <= p is 5 p <= q is 97 97 q <= temp 5

8 selection Sort pseudocode
for(arrayIndex = 0 to numItems -1 ) { for(subarrayIndex = arrayIndex to numItems-1) if (items[subarrayIndex] < items[arrayIndex]) swap items[arrayIndex] and items[arrayIndex] }

9 Practice Run the selection sort coded on the last slide with the Tester class on page 41. Turn in the work before the break


Download ppt "Agenda About the homework EvensAndOdds Array class Array Sorting"

Similar presentations


Ads by Google