//shell排序
public static void shellSort(int[] a){
int dk=a.length/2;
while(dk>=1){
shellInsertSort(a, dk);
dk/=2;
}
}
public static void shellInsertSort(int[] a,int dk){
for(int i=dk;i<a.length;i++){
if(a[i]<a[i-dk]){
int x=a[i];
int j=i-dk;
while(j>=0&&a[j]>x){
a[j+dk]=a[j];
j=j-dk;
}
a[j+dk]=x;
}
}
}
//直接插入排序
public static void insert_sort(int a[]){
int length=a.length;
for(int i=1;i<length;i++){
if(a[i]<a[i-1]){
int x=a[i];
int j=i-1;
while(j>=0&&x<a[j]){
a[j+1]=a[j];
j--;
}
a[j+1]=x;
}
}
}
public static void print(int a[], int n ,int i){
//cout<<i <<":";
System.out.print(i+":");
for(int j= 0; j<8; j++){
//cout<<a[j] <<" ";
System.out.print(a[j]+" ");
}
// cout<<endl;
System.out.println();
}
//简单选择排序
public static void selection_sort(int[] a){
for(int i=0;i<a.length;i++){
int maxIndex=0;
for(int j=0;j<a.length-i;j++){
if(a[j]>a[maxIndex]){
maxIndex=j;
}
}
if(maxIndex!=a.length-i-1){
int temp=a[a.length-i-1];
a[a.length-i-1]=a[maxIndex];
a[maxIndex]=temp;
}
}
}
//快速排序
public static void quickSort(int a[],int low,int high){
if(low<high){
int privot=partation(a, low, high);
quickSort(a, low,privot-1);
quickSort(a, privot+1, high);
}
}
public static int partation(int[] a,int low,int high){
int privotKey=a[low];
print(a);
System.out.println("\n");
while(low<high){
while(low<high&&a[high]>=privotKey){
high--;
}
int temp=a[low];
a[low]=a[high];
a[high]=temp;
while(low<high&&a[low]<=privotKey){
low++;
}
int temp2=a[low];
a[low]=a[high];
a[high]=temp2;
}
//a[low]=privotKey;
print(a);
System.out.println("\n");
return low;
}
public static void print(int[] array){
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
}
//冒泡排序
public static void bubble(int[] a,int length){
for(int i=0;i<length;i++){
for(int j=0;j<length-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
//归并排序
public static void merge_sort(int[] a,int begin,int end,int temp[] ){
if(begin<end){
int mid=(begin+end)/2;
merge_sort(a, begin,mid, temp);
merge_sort(a, mid+1, end, temp);
merge(a, begin, mid, end, temp);
}
}
public static void merge(int[] a,int begin,int mid, int end,int[] temp){
int i=begin;
int j=mid+1;
int k=0;
while(i<=mid&&j<=end){
if(a[i]<=a[j]){
temp[k++]=a[i++];
}else {
temp[k++]=a[j++];
}
}
while(i<=mid){
temp[k++]=a[i++];
}
while(j<=end){
temp[k++]=a[j++];
}
for(i=0;i<k;i++){
a[begin+i]=temp[i];
}
}
public static void InsertSort(int a[], int n)
{
for(int i= 1; i<n; i++){
if(a[i] < a[i-1]){ //若第i个元素大于i-1元素,直接插入。小于的话,移动有序表后插入
int j= i-1;
int x = a[i]; //复制为哨兵,即存储待排序元素
// a[i] = a[i-1]; //先后移一个元素
while(j>=0&&x < a[j]){ //查找在有序表的插入位置
a[j+1] = a[j];
j--; //元素后移
}
a[j+1] = x; //插入到正确位置
}
print(a,n,i); //打印每趟排序的结果
}
}
排序算法
最新推荐文章于 2023-03-17 23:16:58 发布