原文链接:http://blog.csdn.net/mumubumaopao/article/details/51931434
经常会用到排序的算法,比如:冒泡法,选择法,快速排序,二分插入排序等等.前面两个就不说了,贴出来自己写的快速排序和二分插入排序的Swift及Java的代码实现,喜欢的话control+C拿去用.
swift实现快速排序和二分插入排序算法:
(想运行的话,直接复制代码,替换掉控制器里的viewDidLoad方法就好了)
overridefuncviewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
vararray :Array = [2,1,3,5,4,6,8,7,9,10]
//quickSort(&array, left: 0, right: 9)
binarySort(&array)
foriin0... array.count-1{
print(array[i])
}
}
//快速排序
funcquickSort(inoutarray:Array,left:Int,right:Int){
ifleft > right {
return
}
varbase,temp,i,j:Int
i = left
j = right
base = array[left]
whilei < j {
whilearray[j] >= base && i < j {
j -=1
}
whilearray[i] <= base && i < j {
i +=1
}
ifi < j {
temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
array[left] = array[i]
array[i] = base
quickSort(&array, left: left, right: i -1)
quickSort(&array, left: i +1, right: right)
}
//二分插入法排序
funcbinarySort(inoutarray :Array){
varlow,mid,high,base :Int
foriin1... array.count-1{
low =0
high = i -1
base = array[i]
whilelow <= high {
mid = (low + high)/2
ifarray[mid] >= base{
low = mid +1
}elseifarray[mid] <= base{
high = mid -1
}
}
forvarj = i -1; j >= high +1; j -=1{
array[j +1] = array[j]
}
array[high +1] = base;
}
}
Java实现快速排序:
直接贴出来整个类了,毕竟不长,创建新文件把所有代码拷进去就可以运行了.
publicclassSort{
publicstaticvoidquickSort(int[] array,intleft,intright){
if(left > right){
return;
}
intbase,temp,i,j;
i = left;
j = right;
base = array[left];
while(i < j){
while(array[j] <= base && i < j){
j --;
}
while(array[i] >= base && i < j){
i ++;
}
if(i < j){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
array[left] = array[i];
array[i] = base;
quickSort(array,left,i-1);
quickSort(array,i +1,right);
}
publicstaticvoidmain(String[] args){
int[] array =newint[]{2,1,4,3,6,5,8,7,9,10};
quickSort(array,0,9);
for(inti =0; i <10; i ++){
System.out.println(array[i]);
}
}
}
Java实现二分插入法排序:
publicclassBinarySort{
publicstaticvoidmain(String[] args){
int[] array =newint[]{2,3,1,4,6,5,8,7,9,10};
binarySort(array);
for(intnumebr : array){
System.out.println(numebr);
}
}
publicstaticvoidbinarySort(int[] array){
intlow,mid,high,base;
for(inti =1; i < array.length ; i++){
low =0;
high = i -1;
base = array[i];
while(low <= high){
mid = (low + high) /2;
if(array[mid] > base){
low = mid +1;
}elseif(array[mid] < base){
high = mid -1;
}
}
for(intj = i -1; j >= high +1; j -=1){
array[j +1] = array[j];
}
array[high +1] = base;
}
}
}
以上就是使用swift和Java实现的快速排序算法和二分插入算法的实现及测试用例.不足之处,欢迎指正.
加入审核被拒交流群,一起交流审核上架经验吧~~ 群号:689757099