100 likes | 121 Views
Dive into the world of sorting in Java with this comprehensive guide. Learn about different types of items you can sort, explore the mechanics of sorting in Java, and master the built-in sorting methods for arrays and ArrayLists. Discover the nuances of Arrays.sort() and Collections.sort() methods, including their applicability to various data types. Enhance your understanding through exercises on insertion sorting and its implementation. Access additional resources and boost your Java sorting skills today!
E N D
Sorting - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen.jiang@temple.edu
Table of Contents • Introduction to sorting in Java • Types of things you can sort • Exercise
Mechanics of Sorting in Java • Java has built-in ways to sort arrays and ArrayLists: Arrays.sort(myArray); Collections.sort(myArrayList); • Note that these are static methods in the Arrays and Collections classes, NOT instance methods! NOT:myArray.sort(); NOT:myArrayList.sort();
temperatureArray: • After Arrays.sort(temperatureArray):
temperatureArrayList: • After Collections.sort(temperatureArrayList):
Types of things you can sort • The Arrays.sort() method applies to arrays, but arrays have types. • E.g., int[], double[], Object[], Point[] • Arrays.sort() can sort: • any primitive array type • any Object array type that implements the Comparable<T> interface.
The Collections.sort() method applies to ArrayLists, but ArrayLists have types. • E.g., ArrayList<Integer>, ArrayList<Object>, ArrayList<String []> • Likewise, Collections.sort() can sort: • ArrayList<T>, if T implements the Comparable<T> interface
Exercise • Insertion sorting and its implementation • http://www.cis.temple.edu/~jiang/1068practice14.pdf • Partial insertion sorting and its implementation • 2nd prize?
public static int SecondPrize (int [ ] x){int p1, p2;if (x.length<2)return-1;if(x[0]<x[1]) {p1=1; p2=0;}else {p1 = 0; p2=1;}for (int i = 2; i<x.length; i++){ int v = x[i]; if (v>x[p1]){ p2 = p1; p1 = i;} else if (v>x[p2]){ p2 = i;}}return p2; }
Partial insertion sorting and its implementation • 3rd prize?