CS 112 - Fall 2012, Lab 03 Haohan Zhu

advertisement
CS 112 - Fall 2012, Lab 03
Haohan Zhu
CS 112 - Fall 2012, Lab 03
5/30/2016
Random Class
Boston University Slideshow Title Goes Here
 http://docs.oracle.com/javase/7/docs/api/java/util/Random.ht
ml
 Create an object for Random()
 Random r = new Random();
 Use method .nextInt(n) to generate a pseudorandom,
uniformly distributed int value between 0 (inclusive) and the
specified value n (exclusive)
2
CS 112 - Fall 2012, Lab 03
5/30/2016
Evaluation by Time
Boston University Slideshow Title Goes Here
 http://docs.oracle.com/javase/7/docs/api/java/lang/System.ht
ml
 System.nanoTime();
 System.currentTimeMillis();
3
CS 112 - Fall 2012, Lab 03
5/30/2016
Practice: Inversion
Boston University Slideshow Title Goes Here
 Let int A[] be an array of distinct integers. There are
len = A.length distinct integers.
 If i<j and A[i]>A[j], then the pair (i, j) is called an
inversion of A.
 There exists many such pairs in A. Compute how
many inversions in A.
4
CS 112 - Fall 2012, Lab 03
5/30/2016
Practice: Inversion
Boston University Slideshow Title Goes Here
 Intuitive method: O(n^2)
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
5
CS 112 - Fall 2012, Lab 03
5/30/2016
Practice: Inversion
Boston University Slideshow Title Goes Here
 Maximal number of inversions ?
 Find an efficient algorithm
 When the array is partly sorted, to determine how
many inversions are caused by a number, we do not
need to compare every pair of numbers. For instance,
in array {1,3,5,7,2,4,6,8}, consider the number of
inversions caused by 2.
6
CS 112 - Fall 2012, Lab 03
5/30/2016
Practice: Inversion
Boston University Slideshow Title Goes Here
 Use the process similar to merge sort
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
1
3
2
5
7
4
6
8
7
Download