用java实现快速排序和桶排序

一 用Java实现快速排序

采用的思想是递归的思想

import java.util.Scanner;

public class quick {
    private static void quickSort(int[] array, int low, int high) {
        if (low >= high) {
            return;
        }
        int i = low, j = high, temp = array[i]; // 最左边的数作为比较数
        while (i < j) {
            while (i < j && array[j] >= temp) { // 向左寻找第一个小于比较数的数
                j--;
            }
            if (i < j) {
                array[i++] = array[j]; // 将array[j]填入array[i],并将i向右移动
            }
            while (i < j && array[i] < temp) {// 向右寻找第一个大于temp的数
                i++;
            }
            if (i < j) {
                array[j--] = array[i]; // 将array[i]填入array[j],并将j向左移动
            }
        }
        array[i] = temp;
        quickSort(array, low, i - 1);
        quickSort(array, i + 1, high);
    }

    public static void main(String[] args) {
        quick q = new quick();
        int a[] = new int[100];
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        quick.quickSort(a, 0, n - 1);
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
    }
}

二 用Java实现桶排序

package 桶排序;

import java.util.Scanner;

public class demo {

    public void main(String args[])
    {
        int a[]=new int[101];
        for(int i=0;i<a.length;i++)
            a[i]=0;
    Scanner scanner=new Scanner(System.in);
    System.out.println("enter n numbers:");
    int n=scanner.nextInt();
    for(int i=0;i<n;i++)
    {
        int t=scanner.nextInt();
        a[t]++;
    }
    for(int i=0;i<101;i++)
    {
        for(int j=0;j<a[i];j++)
        {
            System.out.print(i+" ");
        }
    }
    scanner.close();
    System.out.println("桶排序就是这样");
    }
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值