100 likes | 102 Views
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.
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?