数据结构知识点复习
插入型排序算法
1.直接插入(稳定,尤其适用于已知输入个数,边输入边排序)
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int n,tag,temp;
while(cin>>n){
//InsertSort seems like the best choice
int num[n];
for(int i=0; i<n; i++){
cin>>num[i];
tag = i;
while(tag>0){
if(num[tag]<num[tag-1]){
temp = num[tag-1];
num[tag-1] = num[tag];
num[tag] = temp;
tag--;
}else
break;
}
}
for(int i=0; i<n; i++)
cout<<num[i]<<" ";
cout<<endl;
}
}
2.折半插入(不稳定)
交换型排序算法
- 冒泡排序
思想:每一趟冒泡,将最大(或最小)的元素放置在最后;
示例代码(Java)
(Ps:因为冒泡比较简单,就从以前的一个大程序里抠了一个出来,本次是将最小的放在最末尾)
for(i=0;i<SymNum-1;i++)
//冒泡次数
for(j=0;j<SymNum-1-i;j++) {
//注意这里的SymNum-1-i,因为已经放到最后的就不参与下一次比较了
if(p[j]<p[j+1]){
tempFlo = p[j];
p[j] = p[j+1];
p[j+1] = tempFlo;
}
}
}
- 快速排序
思想:任取一个元素作为枢纽元,将其他元素与它进行比较,分为左右两个子集,然后在子集内部依次递归,最终有序;
一般快速排序有三种实现方式:
(最简单)每次都取最前面(或者最后面)的元素作为枢纽元,但对于预排序的数据来说会达到O(n*n)的时间复杂度;
(代价较高)每次都随机产生一个枢纽元,这样不会每次都是最坏的情况,但产生随机数的开销也很大;
(常用)三数中值分割法,取数组的第一个元素、最后一个元素、中间元素的中值作为枢纽元;
取第一个元素作为枢纽元实例代码(Java)
int tagPos(int num[], int low, int high){
int tag = num[low];
while(low<high){
while(low<high && num[high]>tag)
high--;
num[low]=num[high];
while(low<high && num[low]<tag)
low++;
num[high]=num[low];
}
num[low]=tag;
return low;
}
void QuickSort(int num[], int low, int high){
if(low<high){
int tl;
tl = tagPos(num,low,high);
QuickSort(num,low,tl-1);
QuickSort(num,tl+1,high);
}
}
三数中值取枢纽元示例代码(Java)
(Ps:目前本人还不会写指针……所以这个是看起来复杂但逻辑比较简单且没有用到指针的代码……等我学会写指针进行各种操作之后再更新简洁版)
int getBigger(int a,int b){
if(a>b)
return a;
else
return b;
}
int getSmaller(int a,int b){
if(a<b)
return a;
else
return b;
}
int getPoint(int array[]){
if(getBigger(array[0],array[array.length/2])< array[array.length-1])
return getBigger(array[0],array[array.length/2]);
else
return getBigger(getSmaller(array[0],array[array.length/2]),array[array.length-1]);
}
int getNode(int array[],int a){
if(array[0] == a)
return 0;
else if(array[array.length - 1] == a)
return array.length - 1;
else
return array.length/2;
}
选择型排序算法
1.简单选择