想搞个快速排序,却用上了ArrayList是不是有点“邪魔外道” ……

本文介绍了一种使用ArrayList来实现类似快速排序的方法。通过定义checkSequence方法确定待排序元素在已排序列表中的位置,并通过quickSortByArrayList方法完成整个排序过程。

想搞个快速排序,却用上了ArrayList是不是有点“邪魔外道” ……

import java.util.ArrayList;
/**
* Created by Monster on 2015/9/13.
* 使用可变数组进行类似于快速排序的排序:
* 方法checkSequen用法:
* 接收一个已排序的可变数组,及一个待比较的值;
* 即可输出这个值在这个已排序的数值中应该插入的位置,即下标;
*
* 方法quickSortByArrayList用法:
* 接收一个未排序的数组,然后新建一个为空的outputArrayList;
* 并对为排序的数组中的每一个元素及outputArrayList使用checkSequen;
* 并按大小插入到outputArrayList中;
* 最后将可变数组转换成数组outputArray输出;
*/
public class QuickSortByArrayList {
int index;
int indexInCheck;

public int checkSequence(ArrayList<Integer> ArrayList,int input){
    for(int i=0;i<ArrayList.size();i++){
        if (input<=ArrayList.get(i)){
            indexInCheck=i;
            break;
        }
        else {
            indexInCheck=-1;
        }
    }
    return indexInCheck;
}


public int[] quickSortByArrayList(int[] inputArray){
    ArrayList<Integer> outputArrayList=new ArrayList<Integer>(0);
    for(int j=0;j<inputArray.length;j++){
        index=checkSequence(outputArrayList,inputArray[j]);
        if(index==-1){
            outputArrayList.add(inputArray[j]);
        }
        else {
            outputArrayList.add(index,inputArray[j]);
        }
    }
    int[] outputArray=new int[outputArrayList.size()];
    for(int i=0;i<outputArrayList.size();i++){
        outputArray[i]=outputArrayList.get(i);
    }
    return outputArray;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值