数据结构与算法

来源:互联网 发布:怎么在淘宝用图片搜索 编辑:程序博客网 时间:2024/05/21 19:25

1.插入排序

  算法描述:两两比较,如果a[i-1]>a[i],那么将a[i]的值与之前的值相比较,直到找到小于a[i]的值的为止,然后进行交换

 

int InsertSort(int a[], int nLen){int i, j, temp;for (i = 1; i < nLen; i++){if (a[i] < a[i - 1]){temp = a[i];for(j = i - 1; a[j] > temp && j >= 0; j--){a[j + 1] = a[j];}a[j + 1] = temp;//因为当循环退出时,已经是j--,因此此处需为a[j+1]}}}
时间复杂度为0(n^2)


2.希尔排序

 算法描述:将整个序列根据增量分为若干个子序列,然后对子序列进行插入排序,这个增量的值逐渐减少为1

此处代码并没有运行过

int ShellSort(int a[], int nLen, int nDelta){int i, j, temp;for (i = 1 + nDelta; i < nLen; i++){if (a[i] < a[i - nDelta]){temp = a[i];for(j = i - nDelta; a[j] > temp && j >= 0; j -= delta){a[j + nDelta] = a[j];}a[j + nDelta] = temp;}}}

3.起泡排序

 算法描述:比较相邻的两个,如果a[i]>a[i+1],则对调,这样就算最大的数放在了最后,然后对n-1个进行如上操作,知道n=0为止

void BubbleSort(int a[], int nLen){int i, j;for (i = 0;i < nLen; i++){for(j = 1; j < nLen - i; j++){if (a[j - 1] > a[j]){swap(&a[j - 1], &a[j]);}}}}

4.快速排序

 算法描述:选取temp = a[0]为比较对象,从high开始,如果a[high]大于temp,则high--,直到a[high]小于temp为止,将a[low]与a[high]对换,然后从low开始,比较a[low]和temp的值,如果小于,则一直++,直到a[low]大于temp为止,将a[low]与a[high]互换

int Partition(int a[], int nLow, int nHigh){int i, j, temp;i = nLow;j = nHigh;temp = a[nLow];while(i < j){while(a[j] > temp && i < j){j--;}a[i] = a[j];while(a[i] < temp && i < j){i++;}a[j] = a[i];}a[j] = temp;return j;}void QuickSort(int a[], int nLow, int nHigh){int n = 0;if (nLow < nHigh){n = Partition(a, nLow, nHigh);QuickSort(a, nLow, n - 1);QuickSort(a, n + 1, nHigh);}}

堆排序:

算法描述:对数组进行创建堆的操作,根据完全二叉树的特性,进行操作



原创粉丝点击