一、交换排序
基本思想:按关键字两两比较顺序表元素,如果发现逆序则交换,直到所有的对象都排好序为止。
// swap sort.cpp : Defines the entry point for the console application.
/*.省略..*/
void BubbleSort(int r[],int size){
bool noswap;
int i,j;
int temp;
for(i=0;i<=size-1;i++) //指(一个元素向上冒泡,直到找到它合适的位置)这个过程的次数,即有多少个元素要进行冒泡操作
{
noswap=true;
for(j=0;j<=size-i-1;j++) //指进行冒泡操作的每一个元素,要经过多少次对比,才能找到合适的位置
{
if(r[j]<r[j+1])
{
temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
noswap=false;
}
}
if(noswap) break; //本次无交换,终止算法
}
}
运行结果:
二、插入排序
直接插入排序:
已升序为例,当插入第i(i>=1)个元素slist[i]时,前面的元素sl[0],sl[1],...,sl[i-1]已经排好序,将sl[i]的关键字从后向前(由大到小)与sl[i-1],sl[i-2],...的关键字进行比较,找到第一个比它小的,则sl[i]直接插到该元素之后。
直接插入排序算法做好情况下的时间复杂度为O(n),最坏情况下的时间复杂度和平均时间复杂度为O(n^2)。
// insertsort.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
void print(int list[],int size){
for(int i=0;i<size;i++)
cout<<list[i]<<'\t';
cout<<endl;
}
void StrInsertSort(int r[],int size)
{
cout<<endl;
cout<<"排序过程:"<<endl;
int temp;
for (int i=1;i<=size-1;i++) //第0个元素是有序的,下标从1开始
{
temp=r[i];int j=i-1; //temp(r[i])与r[i-1]、r[i-2]、...比较
while(temp<r[j])
{
r[j+1]=r[j];
j--; //查找与移动同时进行
}
r[j+1]=temp; //找到第一个比它小的,插到该元素之后
cout<<i<<"次排序:";
print(r,size);
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int size=8;
int list[size]={49,38,65,97,76,13,27,49};
cout<<"未排序表:"<<endl;
print(list,size);
StrInsertSort(list,size);
cout<<"已排序表:"<<endl;
print(list,size);
system("pause");
return 0;
}
对半插入排序:
基本思想:把取到的第i个元素插入到前0到i-1个元素中,因为前i个元素是有序的,所以二分查找是拿第i个元素和前面有序数列中的第mid=(left+right)/2个元素比较,即有序数列中间的那个元素。
void BinaryInsertSort(int r[],int size){
int temp;
int left,right,mid,i,j;
for(i=1;i<=size-1;i++)
{
temp=r[i];
left=0;
right=i-1;
while(right>=left)
{
mid=(left+right)/2;
if(temp<r[mid]) right=mid-1;
else left=mid+1;
}
for(j=i-1;j>=right+1;j--)
{
r[j+1]=r[j];
}
r[right+1]=temp;
cout<<i<<"次排序:";
print(r,size);
}
cout<<endl;
}