本文主要讨论面试中经常会被问到的算法(我猜那些思想这么重要肯定会问吧)
以下所有程序亲自根据教程启发写的,都能正确运行(vs 2008)
这是一个算法的索引:
看英文名字一目了然,就是这些算法。
0.先给一个打印数组的函数Print
Print.h
#include <iostream>
using namespace std;
class SP{
public:
void Print(int table[],int n );
};
void SP::Print(int table[],int n )
{
for (int i = 0; i < n; ++i)
{
cout<<table[i]<<" ";
}
cout<<endl;
}
1.直接插入排序(directInsertSort),直接在头文件中实现(这种编程习惯不好但是只为操作方便)
directInsertSort.h
class DIS
{
public:
void directInsertSort(int table[],int n);
};
void DIS::directInsertSort(int table[],int n)
{
int i,j;
int temp;
for (i=1;i<n;i++)
{
j=i-1;
temp = table[i];
while(j>=0&&temp<table[j])
{
table[j+1] = table[j];
j--;
}
table[j+1] = temp;
}
}
2、堆排序(heapSort)
heapSort.h
class HP
{
public:
void heapSort(int table[],int n);
void heapAdjust(int table[], int s, int n);
};
void swap(int table[],int i,int j)
{
int temp = table[i];
table[i] = table[j];
table[j] = temp;
}
void HP::heapAdjust(int table[], int s, int n)
{
int i,temp;
temp = table[s];
for ( i=2*s ; i < n; i *= 2)
{
if ( i < n &&table[i] < table[i+1])
{
i++;
}
if ( temp >= table[i])
{
break;
}
table[s] = table[i];
s = i;
}
table[s] = temp;
}
void HP::heapSort(int table[],int n)
{
int i;
for ( i = n/2; i>=0; --i)
{
heapAdjust(table,i,n);
}
for ( i = n-1;i>=0;--i)
{
swap(table,0,i);
heapAdjust(table,0,i-1);
}
}
3、快速排序(quickSort),此算法乃排序算法之必考必问,这种思想经常引申出很多算法。
quickSort.h
class QS
{
public:
void quickSort(int table[],int low,int high);
};
void QS::quickSort(int table[],int low,int high)
{
int i,j,pivot;
if (low<high)
{
i = low;
j = high;
pivot = table[i];
//-----------------------------------------------------//
while (pivot<table[j]&&i<j)
j--;
if (i<j)
{
table[i] = table[j];
i++;
}
//------------------------------------------------------//
while(table[i]<pivot&&i<j)
i++;
if (i<j)
{
table[j] = table[i];
j--;
}
//-----------------------------------------------------//
table[i] = pivot;
i++;
j--;
quickSort(table,low,j);
quickSort(table,i,high);
}
}
(上面的分割线只是为了代码更美观,层次和重复部分清楚,看我萌萌哒的内心^_^)
4、希尔排序算法(shellSort)
shellSort.h
class SS
{
public:
void shellSort(int table[],int len);
};
void SS::shellSort(int table[],int len)
{
int i,j,k;
int jump = len/2;
int temp;
for (k=jump;k>0;k>>=1) //k=k/2,减半
{
for (i=k;i<len;i++)
{
temp = table[i];
j = i-k;
while(j>=0&&temp<table[j])
{
table[j+k] = table[j];
j = j - k;
}
table[j+k] = temp;
}
}
}
5、占位,不断更新中===============================================================================
主函数中调用举例:
main.cpp
#include <iostream>
#include "Print.h"
#include "directInsertSort.h" //DS(类名)
#include "heapSort.h" //HS
#include "quickSort.h" //QS 参数(table,low,high)
#include "shellSort.h" //SS
using namespace std;
int main()
{
int table[10] ={10,9,3,4,8,7,6,5,1,2} ;
SS sortMethod; //选择排序方法
SP outPut; //调用打印函数,交换函数
outPut.Print(table,10);
sortMethod.shellSort(table,10);
outPut.Print(table,10);
return 0;
}
这里以希尔排序算法为例简单演示运行结果:
ps:各种算法复杂度一览表(不做多的介绍)