Array Sorting: Bubble and Selection Sort Algorithms
Learn about the Bubble Sort and Selection Sort algorithms for sorting arrays in Java. Practice implementing these algorithms and improve the program. Also, explore the built-in Array class in Java.util.Arrays.
Array Sorting: Bubble and Selection Sort Algorithms
E N D
Presentation Transcript
Agenda • About the homework EvensAndOdds • Array class • Array Sorting Bubble sort Selection sort • practice
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?
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
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); System.out.println("array before sorting: "); for(int dummy : bArry) System.out.print(dummy+ " ");
Bubble Sort Original data Compare the shaded pair. 4>2, so swap Swap completed Compare the shaded pair. No swap needed Compare the shaded pair. 5>1, so swap Swap completed. Compare the shaded pair. 5>3, so swap Swap completed
selection Sort Original data 1st pass: select smallest value in gray area just above.. It’s 1. Then 1 and 4 have now been swapped. 2nd pass: select smallest value in gray area just above.. It’s 2. No swap necessary since the 2 above is less than 3. 3rd pass: select smallest value in gray area just above.. It’s 3. Then 3 and 5 have now been swapped. 4th pass: select smallest value in gray area just above.. It’s 5. No swap necessary since the 4 is less than 5.
Swap method • Original values p = 5; q = 97; • Swapped values p = 97; q=5; • How? temp = p; p = q; q = temp; temp <= p is 5 5 p <= q is 97 97 q <= temp 5
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] } } }
Practice Run the selection sort coded on the last slide with the Tester class on page 41. Turn in the work before the break