经常会用到排序的算法,比如:冒泡法,选择法,快速排序,二分插入排序等等.前面两个就不说了,贴出来自己写的快速排序和二分插入排序的swift及Java的代码实现,喜欢的话control+C拿去用.
swift实现快速排序和二分插入排序算法:
(想运行的话,直接复制代码,替换掉控制器里的viewDidLoad方法就好了)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var array :Array<Int> = [2,1,3,5,4,6,8,7,9,10]
//quickSort(&array, left: 0, right: 9)
binarySort(&array)
for iin 0 ... array.count -1{
print(array[i])
}
}
//快速排序
func quickSort(inout array:Array<Int>,left:Int,right:Int){
if left > right {
return
}
var base,temp,i,j:Int
i = left
j = right
base = array[left]
while i < j {
while array[j] >= base && i < j {
j -= 1
}
while array[i] <= base && i < j {
i += 1
}
if i < 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)
}
//二分插入法排序
func binarySort(inout array :Array<Int>){
var low,mid,high,base :Int
for iin 1 ... array.count -1{
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
}
}
forvar j = i - 1; j >= high +1; j -= 1{
array[j + 1] = array[j]
}
array[high + 1] = base;
}
}
Java实现快速排序:
直接贴出来整个类了,毕竟不长,创建新文件把所有代码拷进去就可以运行了.
public class Sort{
public staticvoid quickSort(int[] array,int left,int right){
if (left > right){
return;
}
int base,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);
}
public staticvoid main(String[] args){
int[] array = new int[]{2,1,4,3,6,5,8,7,9,10};
quickSort(array,0,9);
for(int i =0 ; i < 10 ; i ++){
System.out.println(array[i]);
}
}
}
Java实现二分插入法排序:
public class BinarySort{
public staticvoid main(String[] args){
int[] array = new int[]{2,3,1,4,6,5,8,7,9,10};
binarySort(array);
for(int numebr : array){
System.out.println(numebr);
}
}
public staticvoid binarySort(int[] array){
int low,mid,high,base;
for(int i =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;
}else if (array[mid] < base){
high = mid - 1;
}
}
for (int j = i -1; j >= high + 1; j -=1){
array[j + 1] = array[j];
}
array[high + 1] = base;
}
}
}
以上就是使用swift和Java实现的快速排序算法和二分插入算法的实现及测试用例.不足之处,欢迎指正.