快速排序和插入排序的Java代码实现

public class sortTest {

/**
 * 快速算法
 */
public static int[]   quick_sort(int[] a,int l,int r ){

    if (l < r) {
        int i = l,j = r;
        int X = a[i];
        while (i < j) {
            // 从后向前的与基值比较并排序
            while (i < j && a[j] >= X) {
                j--;
            }
            // 比基值小的向前换位置
            if (i < j) {
                a[i] = a[j];
                i++;
            }
            // 从前向后的与基值比较并排序
            while (i < j && a[i] < X) {
                i++;
            }
            // 比基质大的向后换位置
            if (i < j) {
                a[j] = a[i];
                j--;
            }
        }
        a[i] = X;
        quick_sort(a, l, i-1);
        quick_sort(a, i + 1, r);
    }
    return a;
}

/**
 * 插入排序
 */
public static int[] insert_sort(int[] a){
    for(int i= 1;i< a.length;i++){
        for(int j= i;j>0;j--){
            if(a[j-1]>=a[j]){
                a[j] = a[j-1] + a[j];
                a[j-1] = a[j] - a[j-1];
                a[j] = a[j] - a[j-1];
            }
        }
    }
    return a;
}



public static void main(String[] args) {
    int[] ins = {2,3,5,1,23,6,78,34};
    int[] sortA=  quick_sort(ins,0,ins.length-1);
    int[] sortB=  insert_sort(ins);
    for (int s:sortA) {
        System.out.println(s);
    }
}

}

可以参照这两个 :快速 https://www.runoob.com/w3cnote/quick-sort.html 插入https://blog.csdn.net/qq_28081081/article/details/80594386
https://www.cnblogs.com/skywang12345/p/3596746.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值