排序 堆排序 快排序 插入排序 选择排序

堆排:

public static void heapAdjust(int h[], int s, int m) {
int temp = h[s];
int i=2 * s + 1;
for ( ;i < m;i= 2 * s + 1) {if (i+1 < m && h[i] < h[i+1])
i++;
if (temp > h[i])
break;
h[s] = h[i];
s= i;
h[i] = temp;
}


}


public static void heapSort(int h[]) {
for (int i = h.length / 2; i >= 0; --i)
heapAdjust(h, i, h.length);
for (int i = h.length - 1; i >= 0; i--) {
int temp = h[i];
h[i] = h[0];
h[0] = temp;
heapAdjust(h, 0, i);
}
}


插入排序

public static void insertSort(int[] a, int length) {
int temp;
for (int i = 1; i < length; ++i) {
if (a[i] < a[i - 1]) {
temp = a[i];
a[i] = a[i - 1];
int j = i - 1;
for (; j >= 0 && a[j] > temp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}


public static void BinsertSort(int[] a) {
int temp;
for (int i = 1; i < a.length; ++i) {
temp = a[i];
int low = 0, high = i - 1;
while (low <=high) {
int m = (low + high) / 2;
if (temp < a[m]){
high = m - 1;
System.out.println("i is "+i+", positon is "+high);
}
else{
low = m + 1;
System.out.println("i is "+i+", positon is "+low);
}
}


for (int j = i - 1; j >=high+1; j--) {
a[j+1] = a[j];

}
a[high + 1] = temp;
}
}

归并排序:

static void merge(int SR[],int i,int m,int n){
//将有序的sr[i..m]和sr[m+1..n]归并为有序的tr[i..n]
int L[]=new int[m+1-i];
int R[]=new int[n-m];
for(int l=0;l<=m-i;l++)L[l]=SR[l+i];
for(int l=0;l<=n-m-1;l++)R[l]=SR[l+m+1];
int k=i,l=0,s=0;
for(;l<m+1-i&&s<n-m;++k){
if(L[l]<R[s])SR[k]=L[l++];
else SR[k]=R[s++];
}
if(l<m+1-i)SR[k++]=L[l++];
if(s<n-m)SR[k++]=R[s++];
}
public static void mergeSort(int SR[],int s,int t) throws Exception{
if(s==t)return;
else{
int m=(s+t)/2;
mergeSort(SR,s,m);
mergeSort(SR,m+1,t);
merge(SR,s,m,t);
}
}

快排:

public static int partition(int a[], int low, int high) {
int temp = a[low];
while (low < high) {
while (low < high && a[high] >= temp)
--high;
{
int n = a[high];
a[high] = a[low];
a[low] = n;
}
while (low < high && a[low] <= temp)
++low;
{
int n = a[high];
a[high] = a[low];
a[low] = n;
}
}
return low;
}


public static void quickSort(int a[], int low, int high) {
int partion = partition(a, low, high);
if (low < partion - 1)
quickSort(a, low, partion - 1);
if (partion + 1 < high)
quickSort(a, partion + 1, high);
}

选择排序:

public static void selectSort(int arr[], int length) {
for (int i = 0; i < length; i++) {
int j = selectMinKey(arr, i);
if(j!=i){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}


private static int selectMinKey(int[] arr, int i) {
int min=arr[i];
int minKey=i;
for(int j=i;j<arr.length;j++){
if(min >arr[j]){
minKey=j;
min=arr[j];
}
}
return minKey;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值