Sorting in Java
what we’ll talk about today
An overview of sorting
Sorting methods in the Java library
The enhanced for statement
Ways to compare objects so they can be sorted
Intuitive sorting algorithm (how you would sort)
Selection sort
An overview
Searching large data lists mandates sorting
We assume we can sort once, then search many times
Sorting comes in two main categories
O(n2) and O(n log n)
The O(n2) sorts are faster for shorter lists, or with certain input patterns
The O(n log n) algorithms have quite a bit of overhead, so are more efficient only for longer lists.
Java Sorting methods in the library
In the class Array are several static sort methods that can be used to sort arrays of different types.
import java.util.*;
public class problem2
{
public static void main(String[] args)
{
int[] ar = {10,30,50,40,20};
Arrays.sort(ar);
for(int num=0; num<ar.length; num++)
System.out.println(ar[num]);
} // end main
}
sThe enhanced for statement
Since iterating through an array always takes the same form
for(int num=0; num<ar.length; num++)
System.out.println(ar[num]);
Java 5.0 has included another form of the for statement0
for( int number : ar)
System.out.println(number);
String[] st = {"cat","at","zebra",”henry", "bay"};
Arrays.sort(st);
for(String number : st)
System.out.println(number);
When sorting objects, there must be a way to compare the objects
Usually, the object class will implement the Comparable interface
Sometimes, an alterative method of sorting may be wanted
For instance, a class Person may compare objects by name, so they can be sorted by name
So you call Arrays.sort(personArray)
At times, it list may want to be sorted by SS#
In this case you use a comparator, which is an object of a class that implements the Comparator interface. This has only one method, compare which has two arguments, the two things to be compared. The call to compart obj.compare(a, b) returns an int just as compareTo does.
public class ComparePersons implements Comparator<Person>
public int compare(Person a, Person b)
{ if ( a.getSSN( ) < b.getSSN( ) return -1;
if ( a.getSSN( ) = = b.getSSN( ) return 0;
return 1;
}
then, to sort the list by SSN, call
Arrays.sort(personArray, new ComparePersons)
Let’s look at some sorting algorithms
Sort this list in place, paying careful attention to the steps you used to sort, and count the number of comparisons you must make
42 95 16 63 28 74
If there are 6 items in the list, how many comparisons?
If there are n items in the list, how many comparisons?
n*(n-1)/2
Code for selection sort
public void sort()
{
for (int pos = 0; pos < a.length-1; pos++)
{
int minPos = pos;
for(int i = pos +1; i < a.length; i++)
if(a.[i] < a[minPos]
minPos= i;
swap(minPos, pos);
}
}
private void swap (int i, int j)
{ int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}