import java.io.*;
public class InsertSort {
public static void insertionSort(int []data){
for(int index=1;index<data.length;index++){
int key = data[index];
int position = index;
//将大的值往右移
while(position>0&&data[position-1]>key){
data[position] = data[position-1];
position--;
}
data[position]=key;
}
}
public static void main(String []args){
int []c={4,9,23,1,45,27,5,2};
insertionSort(c);
for(int i=0;i<c.length;i++)
System.out.println("插入排序:"+c[i]);
}
}
2.直接选择排序
import java.io.*;
public class choiceSort {
static void choice(int a[])
{
int temp=0;
for(int i=0;i<a.length-1;i++)
{
temp=a[i];
for(int j=i;j<a.length-1;j++)
{
if(a[j+1]<temp)
{
temp=a[j+1];
a[j+1]=a[i];
a[i]=temp;
}
}
}
}
public static void main(String args[])
{
int a[]={92,28,62,16,56,87,33,66};
choice(a);
for(int i=0;i<a.length-1;i++)
System.out.print(a[i]+" ");
}
}
3.快速排序
import java.io.*;
public class quickSort {
static void quick(int a[],int low,int high)
{
int location;
if(low<high)
{
location=partition(a,low,high);
if(location<high)
quick(a,location+1,high);
if(location>low)
quick(a,low,location-1);
}
}
static int partition(int a[], int low,int high)
{
int key=a[low];
while(low<high)
{
while(low<high&&a[high]>=key)
high--;
a[low]=a[high];
while(low<high&&a[low]<=key)
low++;
a[high]=a[low];
}
a[low]=key; return low;
}
public static void main(String args[])
{
int a[]={67,67,14,52,29,9,90,54,87,71};
quick(a,0,a.length-1);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
4.冒泡排序
import java.io.*;
public class bubbleSort {
static void bubble(int a[])
{
for(int i=0;i<=a.length;i++)
{
for(int j=a.length-1;j>i;j--)
{
if(a[j]<a[j-1])
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}
public static void main(String args[])
{
int a[]={53,33,19,53,3,63,82,20,19,39};
bubble(a);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
5.堆排序
import java.io.*;
public class heapSort {
static void heap(int a[])
{
for(int i= a.length/2; i>0; --i ) // 建堆(大顶堆)
HeapAdjust( a, i, a.length );
for(int i= a.length; i>1; --i )
{
int temp=a[1];
a[1]=a[i];
a[i]=temp;
HeapAdjust(a, 1, i-1 ); // 交换, 重建堆
}
}
static void HeapAdjust(int a[], int s, int m ) {
// 为建大顶堆而进行筛选
int rc =a[s];
for (int j=2*s;j<=m;j*=2 )
{
if (j<m &&(a[j]<a[j+1]))
++j;
if (rc>=a[j])
break;
a[s] =a[j];
s = j;
}
a[s]=rc;
}// HeapAdjust
public static void main(String args[])
{
int a[]={20,12,35,15,10,80,30,17,2,1};
heap(a);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
6.希尔排序
import java.io.*;
public class shellsort {
static void sort(int a[])
{
int step[]={5,3,2,1};
for(int j=0;j<4;j++)
{
for(int k=0;k<step[j];k++)
for(int i=0;i<a.length;i++)
{
if((i+step[j])<a.length&&i%step[j]==k)
if(a[i]>a[i+step[j]])
{
int temp=a[i];
a[i]=a[i+step[j]];
a[i+step[j]]=temp;
}
}
}
}
public static void main(String args[])
{
int a[]={12,89,57,32,96,37,54,5,79,57};
sort(a);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}