您的位置:首页 > 运维架构 > Shell

Java冒泡排序、插入排序、选择排序、shell排序

2012-02-01 09:29 274 查看
int sort[] = new int[5];
sort[0] = 6;
sort[1] = 3;
sort[2] = 8;
sort[3] = 1;
sort[4] = 2;

// 冒泡排序
for(int i=0; i<sort.length; i++) {
for(int j=i+1; j<sort.length; j++) {
if(sort[i] < sort[j]) {//降序排列
int temp = sort[i];
sort[i] = sort[j];
sort[j] = temp;
}
}
}


//选择排序
int temp;
for(int i=0; i<sort.length; i++) {
int lowValue = i;
for(int j=i+1; j<sort.length; j++) {
if(sort[j] > sort[lowValue]) {//降序排列
lowValue = j;
}
}
temp = sort[i];
sort[i] = sort[lowValue];
sort[lowValue] = temp;
}


// 插入排序
int temp;
/* 每拿到一个元素,都要将这个元素与所有它之前的元素遍历比较一遍,
* 让符合排序顺序的元素挨个移动到当前范围内它最应该出现的位置
* */
for(int i=1; i<sort.length; i++) {
for(int j=i; (j>0) && (sort[j] > sort[j-1]); j--) {//sort[j] > sort[j-1]为降序排列
temp = sort[j];
sort[j] = sort[j-1];
sort[j-1] = temp;
}
}


// shell法排序
/*先将数据按照固定的间隔分组,然后排序各个分组的数据,开成以
* 分组来看数据已经排序,从全部数据来看,较小值已经在前面,较大值已经在后面。
* 将初步处理了的分组再用插入排序来排序,那么数据交换和移动的次数会减少。
* 可以得到比插入排序法更高的效率。*/

int j = 0;
int temp = 0;

//分组
for(int increment = sort.length/2; increment > 0; increment /= 2) {

// 每个组内排序
for(int i = increment; i < sort.length; i++) {
temp = sort[i];
for(j = i; j >= increment; j -= increment) {
if(temp > sort[j - increment]) {// 降序排列
sort[j] = sort[j - increment];
} else {
break;
}
}
sort[j] = temp;
}
}


以上四种方法为本人整理所得,若有不对处请各位指出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐