作者: 罗利华 时间: 2013-1-13 17:26
public class SortTest {
public static void main(String[] args) {
int[] x = new int[] { 1, 9, 7, 3, 5};
insert(x);
shell(x);
}
// 插入排序
public static void insert(int[] x) {
for (int i = 1; i < x.length; i++) {
// i从一开始,因为第一个数已经是排好序的啦
for (int j = i; j > 0; j--) {
if (x[j] < x[j - 1]) {
int temp = x[j];
x[j] = x[j - 1];
x[j - 1] = temp;
}
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 希尔排序
public static void shell(int[] x) {
// 分组
for (int increment = x.length / 2; increment > 0; increment /= 2) {
// 每个组内排序
for (int i = increment; i < x.length; i++) {
int temp = x[i];
int j = 0;
for (j = i; j >= increment; j -= increment) {
if (temp < x[j - increment]) {
x[j] = x[j - increment];
} else {
break;
}
}
x[j] = temp;
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
}
没事可以看下,作者: 汪平乐 时间: 2013-1-14 02:14
四种排序方法都齐了,冒泡.选择,插入,希尔下面是补充兄台的选择和自己习惯用的希尔
选择for嵌套循环
public static void select(int[] a)
{
int tmp =0 ;
for (int i = 0; i <a.length-1; i++ ) //比较次数
{
for (int j = i+1;j < a.length;j++ ) //元素的个数
{
if (a[i]>a[j])
{
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
}
希尔
public void sort1(double[] a, int incr[]) {
int span;// 增量
int alen = a.length;// 数组个数
for (int i = 0; i < incr.length; i++) {//增量个数次
span = incr[i];
for (int j = 0; j < span; j++) {
for (int k = 0; k < alen - span; k += span) {//组内直接插入排序
int p = k;
double temp = a[k+span];//current
while( p >=0 && a[p] > temp){
a[p+span] = a[p];
p -=span;
}
a[p + span] = temp;
}
}
}
}
希望可以有帮助...