一.直接插入排序
基本思想:每一步将一个待排序元素按照其关键字值的大小插入到已排序序列的合适位置上,知道待排序元素插入完为止。
template<class T>
void insert_sort(T a[],int n){
for(int i=0;i<n;i++){
T temp=a[i];
int j=i;
while(j>0&&temp<a[j-1]){
a[j]=a[j-1];
j--;
}
a[j]=temp;
}
}
二:选择排序
基本思想:两两比较待排序序列中的元素,并交换不满足顺序要求的各对元素。
template<class T>
void my_swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
template<class T>
void selectionSort(T a[], int n) {
for (int i = 0; i < n; i++) {
int least_index = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[least_index]) //找到最小值
least_index = j;
}
my_swap(a[i], a[least_index]);
}
}
三:冒泡排序
基本思想:每一轮从待排序序列中找到一个最值(最大或者最小),然后将其和第i个位置的元素交换。
template<class T>
void my_swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
template<class T>
void bubbleSort(T a[], int n) {
int i=n-1;
while(i>0){
int least_index=0;
for(int j=0;j<i;j++){
if(a[j]>a[j+1]){
my_swap(a[j],a[j+1]);
least_index=j;//记录最后一次交换的下标,这个下标将用于下一组for循环的判断条件
}
}
i=least_index;
}
}
四:折半查找
//使用这个排序的前提是已经从小到大排好序,必须是从小到大,否则下面这个程序就得做出相应调整
template<class T>
int search(const T a[],int n,const T&key){
int low=0;
int high=n-1;
while(low<=high){
int mid=(low+high)/2;
if(key==a[mid]) {
cout<<"元素的位置为:"<<mid+1<<endl;
break;
}
else if(key<a[mid]) high=mid-1;
else
low=mid+1;
}
if(low>high) cout<<"您要查找的元素不存在"<<endl;
}