快速排序 Java的实现与思路

快速排序与归并排序类似,只不过他是在不断的寻找数组中的基准位置(基准位置左边的元素比基准小右边的比基准大),在以基准为中点对左和右两个数组去找基准直到当前层的数组达到最小,那么此时数组每个位置都满足基准位置那么数组已经排序成功。

代码:

public class suanfa4 {

    public static void main(String[] args) {
        int[] ints = {1,1,5,3,2,5,4,8};
        quicklySort(ints,0,ints.length-1);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }

    public static void quicklySort(int[] temp,int low,int hight){
        if (low<hight){
            int index = marge(temp,low,hight);

            quicklySort(temp,low,index-1);
            quicklySort(temp,index+1,hight);
        }

    }

    private static int marge(int[] temp, int low, int higth) {
        int key = temp[low];

        while(low<higth){
            while (temp[higth]>=key&&low<higth)
                higth--;
            temp[low] = temp[higth];
            while (temp[low]<=key&&low<higth)
                low++;
            temp[higth] = temp[low];
        }

        temp[low]=key;

        return low;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
快速排序是一种常用的排序算法,它的实现思路是通过分治的方式将一个大的数组分成两个子数组,然后对子数组进行递归排序,最终将整个数组排序完成。 Java实现快速排序的步骤如下: 1. 选择一个基准元素,通常是数组的第一个元素。 2. 将数组分成两个子数组,一个子数组中的元素都小于基准元素,另一个子数组中的元素都大于基准元素。 3. 对两个子数组进行递归排序,直到子数组的长度为1或。 4. 将排好序的子数组合并成一个有序的数组。 Java代码实现: public class QuickSort { public static void quickSort(int[] arr, int left, int right) { if (left < right) { int pivotIndex = partition(arr, left, right); quickSort(arr, left, pivotIndex - 1); quickSort(arr, pivotIndex + 1, right); } } private static int partition(int[] arr, int left, int right) { int pivot = arr[left]; int i = left + 1; int j = right; while (i <= j) { while (i <= j && arr[i] <= pivot) { i++; } while (i <= j && arr[j] > pivot) { j--; } if (i < j) { swap(arr, i, j); } } swap(arr, left, j); return j; } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2, 7, 1, 10}; quickSort(arr, , arr.length - 1); System.out.println(Arrays.toString(arr)); } } 在这个实现中,partition方法用于将数组分成两个子数组,quickSort方法用于递归排序子数组,swap方法用于交换数组中的两个元素。最终,我们可以通过调用quickSort方法对数组进行排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值