java 排序的代码_java常用四种排序源代码

选择排序

public class ChooseSort {

publicstatic voidmain(String[] args) {

int[]x = { 2, 332, 16, 575, 203, 4, 23, 11, 345, 32 };

ChooseSort cs = new ChooseSort();

cs.selectSort(x);

for(int i = 0; i < x.length; i++) {

System.out.print(x[i] + "  ");

}

}

publicstatic voidselectSort(int[] a) {

intminIndex = 0;

inttemp = 0;

if((a == null) || (a.length == 0))

return;

for(int i = 0; i < a.length; i++) {

minIndex = i;//无序区的最小数据数组下标

for(int j = i + 1; j < a.length; j++) {//在无序区中找到最小数据并保存其数组下标

if (a[j] < a[minIndex]) {

minIndex = j;

}

}

if(minIndex != i) {//如果不是无序区的最小值位置不是默认的第一个数据,则交换之。

temp = a[i];

a[i] = a[minIndex];

a[minIndex] = temp;

}

}

}

}

插入排序

public class InsertSort {

publicstatic voidmain(String[] args) {

inta[]={ 2, 332, 16, 575, 203, 4, 23, 11, 345, 32 };;

InsertSort is=new InsertSort();

is.sort(a);

for(int i=0;i

System.out.print(a[i]+"  ");

}

}

publicvoid sort(intobj[]){

for(int j=1;j

intkey=obj[j];

inti=j-1;

while(i>=0&&obj[i]>key){

obj[i+1]=obj[i];

i--;

}

obj[i+1]=key;

}

}

}

冒泡排序

public class BubbleSort {

publicvoid bubbleSort(int a[]){

intn=a.length;

for(int i=0;i

for(int j=0;j

if(a[j]>a[j+1]){

int temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}

}

}

publicstatic voidmain(String[] args){

BubbleSort bs=new BubbleSort();

inta[]={ 2, 332, 16, 575, 203, 4, 23, 11, 345, 32 };

bs.bubbleSort(a);

for(int m = 0; m < a.length; m++) {

System.out.print(a[m] + "  ");

}

}

}

快速排序

public class QuickSort {

publicstatic voidmain(String[] args) {

int[]strVoid = { 2, 332,16, 575, 203, 4, 23, 11, 345, 32 };

QuickSort sort = new QuickSort();

sort.quickSort(strVoid, 0, strVoid.length - 1);

for(int m = 0; m

System.out.print(strVoid[m] + "  ");

}

}

publicvoid quickSort(int strDate[], intleft, int right) {

inti, j;

i = left;

j = right;

intmiddle = strDate[(i)];

while(i < j) {

inttempDate = 0;

while(i < j && strDate[j] >= middle) {

j = j - 1;

}

tempDate = strDate[j];

strDate[j] = strDate[i];

strDate[i] = tempDate;

while(i < j && strDate[i] < middle) {

i = i + 1;

}

tempDate = strDate[j];

strDate[j] = strDate[i];

strDate[i] = tempDate;

}

strDate[i] = middle;

if(left < i - 1) {

quickSort(strDate, left, i -1);

}

if(right > i + 1) {

quickSort(strDate, i + 1,right);

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值