学习数据结构与算法是提高编程内力重要途径,从类库入手开始学习编程思想……
一般都是先找一本数据结构的书先过一遍,然后用Java实现这些算法。这是先知道思想,再到实践的过程……可以考虑换种学习方式,先学具体实现算法代码,再到升华为自己解决问题的思路。
一、Arrays类,用的比较多!先写过简单数组排序:
import java.util.*;
public class Text1 {
public static void main (String[] args) {
int[] a={1,9,8,7,1,0,0,4};
Arrays.sort(a);
for(int i:a)
System.out.print (i);
}
}
结果:00114789
二、看下类库是怎么实现sort()方法:
package philn.util;
public class Arrays {
public static void sort(int[] a) {
sort1(a, 0, a.length);
}
private static void sort1(int x[], int off, int len) {
// Insertion sort on smallest arrays
if (len < 7) {
for (int i=off; i<len+off; i++)
for (int j=i; j>off && x[j-1]>x[j]; j--)
swap(x, j, j-1);
return;
}
// Choose a partition element, v
int m = off + (len >> 1); // Small arrays, middle element
if (len > 7) {
int l = off;
int n = off + len - 1;
if (len > 40) { // Big arrays, pseudomedian of 9
int s = len/8;
l = med3(x, l, l+s, l+2*s);
m = med3(x, m-s, m, m+s);
n = med3(x, n-2*s, n-s, n);
}
m = med3(x, l, m, n); // Mid-size, med of 3
}
int v = x[m];
// Establish Invariant: v* (<v)* (>v)* v*
int a = off, b = a, c = off + len - 1, d = c;
while(true) {
while (b <= c && x[b] <= v) {
if (x[b] == v)
swap(x, a++, b);
b++;
}
while (c >= b && x[c] >= v) {
if (x[c] == v)
swap(x, c, d--);
c--;
}
if (b > c)
break;
swap(x, b++, c--);
}
// Swap partition elements back to middle
int s, n = off + len;
s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s);
s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s);
// Recursively sort non-partition-elements
if ((s = b-a) > 1)
sort1(x, off, s);
if ((s = d-c) > 1)
sort1(x, n-s, s);
}
/**
* Swaps x[a] with x[b].
*/
private static void swap(int x[], int a, int b) {
int t = x[a];
x[a] = x[b];
x[b] = t;
}
private static void vecswap(int x[], int a, int b, int n) {
for (int i=0; i<n; i++, a++, b++)
swap(x, a, b);
}
private static int med3(int x[], int a, int b, int c) {
return (x[a] < x[b] ?
(x[b] < x[c] ? b : x[a] < x[c] ? c : a) :
(x[b] > x[c] ? b : x[a] > x[c] ? c : a));
}
}
领会上面代码写的思路……
最后测试下,哈哈
import philn.util.*;
public class Text4 {
public static void main (String[] args) {
int[] a={1,9,8,7,1,0,0,4};
TestArrays.sort(a);
for(int i:a)
System.out.print (i);
}
}
结果:00114789