1.简单插入排序
public class Insertion {
/**
* @param args
*/
public static void insertion_Sort(int a[])
{
int temp = 0;
for(int i=1;i<a.length;i++)
{
temp = a[i];
int j = i-1;
while(j>=0 && a[j]>temp)
{
a[j+1] = a[j];
j--;
}
a[++j] = temp;
}
}
2.选择排序
/*
这种方法,我觉得又可以叫做错位排序
外层循环和内层循环的长度都是length-1,外层从i到length-2;内层从i+1到length-1。
时间复杂度:O(n2)
*/
public class Selection {
/**
* @param args
*/
public static void selection_Sort(int a[])
{
int temp = 0;
for(int i=0;i<a.length-1;i++)
for(int j=i+1;j<a.length;j++)
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
3.冒泡排序(改进)
public static void bubble_Sort(int a[])
{
int temp = 0;
int count=0;
for(int i=0;i<a.length;i++)
{
boolean change=true;
for(int j=0;j<a.length-i-1;j++)
{
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
change=false;
}
}
if(change)
{
break;
}
count++;
}
}
4.计数排序
public static void count_Sort(int a[])
{
int count;
int b[] = new int[a.length];
for(int i=0;i<a.length;i++)
{
count = 0;
for(int j=0;j<a.length;j++)
{
if(a[i]>a[j])
count++;
if(a[i]==a[j] && i>j)
count++;
}
b[count] = a[i];
}
for(int n=0;n<a.length;n++)
a[n] = b[n];
}
5.归并排序
public static void merge_Sort(int a[])
{
int temp[] = new int[a.length];
merge_Sort(a,temp,0,a.length-1);
}
private static void merge_Sort(int a[],int temp[],int l,int r)
{
int mid = (l+r)/2;
if(l==r) return;
merge_Sort(a,temp,l,mid);
merge_Sort(a,temp,mid+1,r);
for(int i=l;i<=r;i++)
temp[i] = a[i];
int i1 = l;
int i2 = mid+1;
for(int j=l;j<=r;j++)
{
if(i1==mid+1)
a[j] = temp[i2++];
else if(i2>r)
a[j] = temp[i1++];
else if(temp[i1]<temp[i2])
a[j] = temp[i1++];
else
a[j] = temp[i2++];
}
}
6.堆排序
public class HeapSort
{
void adjust(int a[],int length,int m)
{
int k;
int i = m;
int j = 2*m;
while(j<length)
{
k = max(a,length,j,j+1);
if(a[i]<a[k])
{
int temp = a[i];
a[i] = a[k];
a[k] = temp;
i = k;
j = 2*i;
}
else break;
}
}
private int max(int a[],int length,int i,int j)
{
if(j==length) return i;
return a[i]>a[j] ? i : j;
}
public void heap_Sort(int a[])
{
for(int i=a.length/2;i>=1;i--)
this.adjust(a,a.length,i);
for(int i=a.length-1;i>=1;i--)
{
int temp = a[1];
a[1] = a[i];
a[i] = temp;
this.adjust(a,i,1);
}
}
}