您的位置:首页 > 其它

经典排序算法回顾:插入排序,冒泡排序

2014-10-30 22:38 393 查看
1.冒泡排序:

//第二种方法是通过不遍历有序数组来减少遍历次数,还有第三种方法:同时左右遍历,减少遍历次数
//sort the array bubbleWay:(the normal way)
- (void) InsertSort(int *a){
int n = strlen(a);
for(int i; i<n; i++){
for(int j; j<n-i-1; j++){
if(r[j]>r[j+1]){
int tmp = a[j];
a[j] = a[j+1];
a[j+1] =tmp;
}
}
}
}

//sort the array bubleWay:(the better way)
- (void) InsertSort(int *a){
int n = strlen(a);
int i = n-1;
while(i>0){
int pos = 0;
for(int j=0; j<i; j++){
if(r[j]>r[j+1]){
pos = j;
int tmp = r[j];
r[j] = r[j+1];
r[j+1] = tmp;
}
}
i = pos;
}
}


2.插入排序:(顺带看了一遍,希尔不稳定排序算法原理)

//还有二分插入,2-路插入排序,只是按照插入的方式不一样的更加高效方法
//交换的方式可以位移√,可以直接交换
1 //sort the array insertWay:(the normal way,the second bubbleWay)
- (void) InsertSort(int *a){
int n = strlen(a);
if(a == nil || n <= 1)return;
for(int i=1; i<n; i++){
int j = i;
int tmp = a[i];
while(j && temp<a[j-1]){
a[j]=a[j-1];
j--;
}
a[j]=a[j-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐