package com;
public class B {
public static void stort(int [] l){//希尔排序
int n=l.length;
for(int g=n/2;g>0;g=g/2){//计算步长,第一次最复杂,因为分了很多组,当步长越来越小,分的组个数也越来越小,组里面数据也越来越多,当然要排序的数据也越来越小,
//有没有考虑过一个问题,当数组个数单数怎么办,不用担心,第二个循环 k<n会处理的
for(int j=0;j<g;j++){
for(int k=j+g;k<n;k+=g){///这里是插入算法,默认第一个数是一个有序序列,从第二个开始排序
if(l[k]<l[k-g]){//增加判断的目的是 如果当前数小于前面一个数,要从新插入排序,因为前面的数组已经是一个有序序列,减少排序过程
int temp=l[k];
int m=k-g;
while(m>=0&&l[m] > temp){// ,g是步长,看过插入算法 的 可以理解成1,
l[m+g] = l[m];
m-=g;
}
l[m+g]=temp;
}
}
}
}
}
public static void stort2(int [] l){//希尔排序
int n=l.length;
for(int g=n/2;g>0;g=g/2){
for(int j=0;j<g;j++){
for(int k=j+g;k<n;k+=g){//使用冒泡排序实现
for(int c=0;c<n-g;c+=g){
if(l[c]>l[c+g]){
int temp=l[c+g];
l[c+g]=l[c];
l[c]=temp;
}
}
}
}
}
}
public static void main(String[] args) {
int [] l={3,1,5,2,6,0,9,4,8,7};
//stort(l);
boundary(l,0,9);
// stort2(l);
for(int ff:l){
System.out.println(ff);
}
}
public static void stort1(int [] l){//冒泡排序
int n=l.length;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(l[j]<l[j+1]){
int temp=l[j];
l[j]=l[j+1];
l[j+1]=temp;
}
}
}
}
static void insertion_sort(int a[])
{ //插入排序
int i,j,tmp;
for (i = 1; i <a.length; i++) {
tmp = a[i];
for (j = i - 1; j >= 0 && a[j] > tmp; j--) {
a[j+1] = a[j];
}
a[j+1] = tmp;
}
}
static void boundary (int [] l,int startIndex, int endIndex){//递归算法
if (startIndex >= endIndex) {
return;
}
int tmp=l[startIndex];
int i=startIndex;
int j=endIndex;
while(i<j){
while(l[j]<=tmp&&i<j){
j--;
}
l[i]=l[j];
while(l[i]>=tmp&&i<j){
i++;
}
l[j]=l[i];
}
l[i]=tmp;
boundary(l,startIndex,i-1);
boundary(l,i+1,endIndex);
}
}
希尔排序,我看网上都是用插入实现的,我试着用冒泡实现
最新推荐文章于 2024-11-28 13:35:01 发布