原文鏈接:http://blog.csdn.net/mumubumaopao/article/details/51931434
經(jīng)常會(huì)用到排序的算法,比如:冒泡法,選擇法,快速排序,二分插入排序等等.前面兩個(gè)就不說(shuō)了,貼出來(lái)自己寫(xiě)的快速排序和二分插入排序的Swift及Java的代碼實(shí)現(xiàn),喜歡的話control+C拿去用.
swift實(shí)現(xiàn)快速排序和二分插入排序算法:
(想運(yùn)行的話,直接復(fù)制代碼,替換掉控制器里的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實(shí)現(xiàn)快速排序:
直接貼出來(lái)整個(gè)類了,畢竟不長(zhǎng),創(chuàng)建新文件把所有代碼拷進(jìn)去就可以運(yùn)行了.
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實(shí)現(xiàn)二分插入法排序:
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實(shí)現(xiàn)的快速排序算法和二分插入算法的實(shí)現(xiàn)及測(cè)試用例.不足之處,歡迎指正.
加入審核被拒交流群笛丙,一起交流審核上架經(jīng)驗(yàn)吧~~ 群號(hào):689757099