八大排序源码

输出数组
public static void showarray(int[] array) //输出数组
{
for (int i:array) {System.out.print("<"+i);}
System.out.print("\n");
}
交换位置
public static void swap(int[] array ,int a,int b) {//交换位置
int temp=array[a];
array[a]=array[b];
array[b]=temp;
}
归并排序
public static void merge(int[] array,int left,int mid,int right) {//归并
int i=left;
int j=mid+1;
int t=0;
int[] temp=new int[right-left + 1];
while(i<=mid&&j<=right) {
if(array[i]<array[j]) {temp[t++]=array[i++];}
else {temp[t++]=array[j++];}
}
while(i<=mid) {temp[t++]=array[i++];}
while(j<=right){temp[t++]=array[j++];}
t=0;
while(left<=right) {array[left++]=temp[t++];}
}
public static void mergeSort(int[] array,int low,int high) {//归并排序
int mid=(low+high)/2;
if(low<high) {
mergeSort(array,low,mid);
mergeSort(array,mid+1,high);
merge(array,low,mid,high);
}
}
堆排序
public static void adjustHeap(int[] array ,int i,int len) {//调整大顶堆
int temp=array[i];
for(int k=i2+1;k<len;k=2k+1) {
if(array[k]<array[k+1]&&k+1<len) {k++;}
if(array[k]>temp) {array[i]=array[k];i=k;}
else {break;}
}
array[i]=temp;
}
public static void heapSort(int[] array) { //堆排序
for(int i=array.length/2-1;i>=0;i–) {
adjustHeap(array,i,array.length);
}
for(int j=array.length-1;j>0;j–) {
swap(array,0,j);
adjustHeap(array,0,j);
}
}
冒泡排序
public static void bubbleSort(int[] array)//冒泡排序
{
int len = array.length;
boolean flag = true;
while (flag) {
flag = false;
for (int i = 0; i < len - 1; i++) {
if (array[i] > array[i + 1]) {
swap(array,i,i+1);
flag = true;
}
}
len–;
}
}
快速排序
public static void quickSort(int[] array, int left, int right) //快速排序
{
if(left<right) {
int low=left;
int high=right;
int key=array[left];
while(low<high) {
while(low<high&&array[high]>=key) {high–;}
array[low]=array[high];
while(low<high&&array[low]<=key) {low++;}
array[high]=array[low];
}
array[low] = key;
quickSort(array, left, low - 1);
quickSort(array, low + 1, right);
}
}
插入排序
public static void insertSort(int[] array) { //插入排序
for (int i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) {
int temp = array[i];
int j;
for ( j = i - 1; j >= 0 && temp < array[j]; j–)
{array[j + 1] = array[j];}
array[j + 1] = temp;}}}
public static void shellSort(int[] array) { //希尔排序
int n = array.length;
for(int h=n/2;h>0;h/=2) {
for(int i=h;i<n;i++) {
for(int j=i-h;j>=0;j-=h) {
if(array[j]>array[j+h])
{swap(array,j,j+h);}}}}}
选择排序
public static void selectSort(int[] array) {//选择排序
int i,j;
for(i=0;i<=array.length-1;i++)
{
int k=i;
for(j=i+1;j<=array.length-1;j++) {
if(array[k]>array[j])
k=j;
}
swap(array,i,k);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值